Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30436
  • 博文数量: 11
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 131
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-14 19:23
个人简介

a person

文章分类

全部博文(11)

文章存档

2015年(11)

我的朋友

分类: C/C++

2015-04-27 21:55:19

Exponential backoff (指数退避)
在Socket连接中用到该算法的代码片段:

点击(此处)折叠或打开

  1. #include <unistd.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>

  4. #define MAXSLEEP 128

  5. int connect_retry(int domain,int type,int protocol,const struct sockaddr *addr,socklen_t alen){
  6.     int numsec,fd;
  7.     /* Try to connect with exponential backoff */
  8.     for(numsec=1; numsec <= MAXSLEEP; numsec <<= 1){
  9.         if((fd = socket(domain, type, protocol)) < 0 )
  10.             return(-1);
  11.         if(connect(fd, addr, alen) == 0){
  12.             /* Connection accepted. */
  13.             return(fd);
  14.         }
  15.         close(fd);
  16.         /* Delay before trying again */
  17.         if(numsec <= MAXSLEEP/2)
  18.             sleep(numsec);
  19.     }
  20.     return(-1);
  21. }



阅读(2004) | 评论(0) | 转发(0) |
0

上一篇:writen and readn

下一篇:socket

给主人留下些什么吧!~~