睡眠功能是睡眠所有线程还是只调用它的人?

时间:2012-08-11 13:59:10

标签: c multithreading pthreads sleep thread-sleep

我在linux(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);
}

2 个答案:

答案 0 :(得分:9)

The standard拼写它:

  

sleep()函数将导致调用线程   暂停执行直到....

linux同样明确:

  

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

但是有一些错误的引用会另外保留。 linux.die.net用于声明sleep导致进程等待。

答案 1 :(得分:4)

只是调用该函数的线程。