2012-08-11 69 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