我聽說有些unix實現使用alarm(2)
來實現sleep
函數。 如果這是真的,我想下面的代碼可能不安全,因爲SIGALRM
可能被髮送到進程,這是由根線程接收。在線程中調用sleep(3),usleep(3)或nanosleep(2)是否安全?
#include <pthread.h>
#include <unistd.h>
void *doit(void *arg) {
sleep(1);
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t th;
pthread_create(&th, NULL, doit, NULL);
sleep(5);
pthread_join(th, NULL);
return 0;
}
它是安全的調用sleep(3)
,usleep(3)
或nanosleep(2)
螺紋?
可能的重複[Does calling sleep()from pthre廣告把線程睡覺或進程?](http://stackoverflow.com/questions/6192645/does-calling-sleep-from-pthread-put-thread-to-sleep-or-process) –
你可以閱讀[ posix](http://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html)不得不說。特別參見「基本原理」部分。 – Duck