最近在阅读 libev 的源码,看到 libev 的代码里面的 sleep 实现, 我觉得可以把这个 sleep 实现单独拿出来,作为参考,以后可以直接拿来用。
代码如下(稍有修改):
void ev_sleep (double delay) { if (delay > 0.) { #if EV_USE_NANOSLEEP struct timespec ts; //EV_TS_SET (ts, delay); ts.tv_sec = (long)t; ts.tv_nsec = (long)((t - ts.tv_sec) * 1e9); nanosleep (&ts, 0); #elif defined _WIN32 Sleep ((unsigned long)(delay * 1e3)); #else struct timeval tv; /* here we rely on sys/time.h + sys/types.h + unistd.h providing select */ /* something not guaranteed by newer posix versions, but guaranteed */ /* by older ones */ //EV_TV_SET (tv, delay); tv.tv_sec = (long)t; tv.tv_usec = (long)((t - tv.tv_sec) * 1e6); select (0, 0, 0, 0, &tv); #endif } }
其中的 EV_TS_SET 和 EV_TV_SET 是两个宏定义,我直接把这两个宏展开了。