2012-08-11 102 views
7

我正在用Linux上的pthread编程(Centos)?我想要线程睡一会儿等待什么。我正在尝试使用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); 
} 
+0

只有来电者 – bestsss 2012-08-11 14:01:47

+1

@Kiril,来吧去检查他的问题历史。这是一个单一的班轮回答 – bestsss 2012-08-11 14:03:21

+0

我的意思是“工作”,而不是“警告”。 @bestsss - 要检查什么?我没有提到这个问题,我甚至投了赞成票。 – 2012-08-11 14:33:53

回答

9

The standard阐明它:

睡眠()函数须安排调用线程是 从执行,直到悬浮....

linux一个同样明显:

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

然而,有一些错误的参考,否则保持不变。 linux.die.net用于陈述sleep导致进程等待。

+3

但睡眠()函数似乎使主线程睡眠 – 2012-08-11 14:20:33

+1

@NickDong它使**调用线程**睡眠。 – cnicutar 2012-08-11 14:21:26

+0

谢谢,我会再试一次。 – 2012-08-11 14:41:03

3

只要它调用函数的线程。

+0

你有没有测试过?在我的测试程序中,它似乎让主线程睡眠。 – 2012-08-11 14:40:00

+0

是的,我测试过了。我也读过这些函数的文档。 – jalf 2012-08-11 15:26:05

+0

@jalf 100%正确。如果Sleep()调用使主线程休眠,则主线程直接调用它或正在等待睡眠后仅由睡眠线程提供的其他信号。 – 2012-08-11 19:10:33