睡眠函数会让所有线程都休眠,还是只有调用它的线程休眠?

12

我正在使用CentOS上的pthread进行编程,需要让线程短暂地休眠以等待某些操作。我尝试使用sleep()、nanosleep()或usleep()等函数来实现。请问,这些函数是让所有线程都休眠还是只有调用它的线程休眠?如果您有任何建议或参考资料,将不胜感激。

void *start_routine () {
    /* I just call sleep functions here */
    sleep (1); /* sleep all threads or just the one who call it? 
                  what about nanosleep(), usleep(), actually I 
                  want the threads who call sleep function can 
                  sleep with micro-seconds or mili-seconds.  
               */
    ...
}

int main (int argc, char **argv) {
    /* I just create threads here */
    pthread_create (... ...);
    ...
    return 0;
}

我的测试程序:

#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>

void *start_routine (void *j) {

    unsigned long sum;
    int i;
    int jj;
    jj = (int)j;
    do {
        sum = 1;
        for (i=0; i<10000000; i++) {
            sum = sum * (sum+i);
        }
        if (jj == 0) {
            printf ("\033[22;33m[jj%d.%ld]\t", jj, sum);
            sleep(1);           
        }
        else {
            printf ("\033[22;34m[jj%d.%ld]\t", jj, sum);
        }

    }while (1);

    pthread_exit((void *)0);
}
int main(int argc, char *argv[])
{
    cpu_set_t cpuset;
    pthread_t thread[2];
    int i;
    i = 0;
    CPU_ZERO(&cpuset);
    CPU_SET(i, &cpuset);

    pthread_create (&thread[0], NULL, start_routine, (void *)i);
    pthread_setaffinity_np(thread[0], sizeof(cpu_set_t), &cpuset);
    i = 1;
    CPU_ZERO(&cpuset);
    CPU_SET(i, &cpuset);
    pthread_create (&thread[1], NULL, start_routine, (void *)i);
    pthread_setaffinity_np(thread[1], sizeof(cpu_set_t), &cpuset);
    pthread_exit (NULL);
}

1
@Kiril,快去查看他的问题历史记录。这是一个单行回答。 - bestsss
我的意思是“工作”,而不是“警告”。@bestsss - 要检查什么?我还没有对这个问题说过任何话,甚至还点了赞。 - Kiril Kirov
为什么你想要调用 sleep 函数? - Peter Ritchie
2个回答

17

标准中明确规定:

sleep() 函数将导致调用线程被挂起,直到...

Linux 的文档也同样清晰明了:

sleep()调用线程休眠直到...

然而,还有一些错误的参考资料坚称sleep会使进程等待。


我发现我的 Red Hat Enterprise Linux Workstation release 6.6 系统的 sleep(3)手册上写着,“sleep() 会使调用进程休眠直到...”,因此或许上游的手册已经更新。 - bgoodr

7

只有调用该函数的线程。


你测试过那个吗?在我的测试程序中,它似乎会让主线程睡眠。 - Nick Dong
是的,我已经测试过了。我也阅读了函数的文档。 - jalf
@jalf 是100%正确的。如果Sleep()调用使主线程休眠,那么主线程直接调用它或者正在等待一些其他信号,这些信号只有在休眠线程休眠后才会提供。 - Martin James
你能在这里发布你的测试程序吗?我已经发布了我的,但是结果让我感到困惑。 - Nick Dong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接