10

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);
}
4

2 に答える 2

15

標準はそれを綴ります:

sleep() 関数は、呼び出しスレッドの実行を .... まで中断させます。

Linuxのものは同じくらい明確です:

sleep()呼び出しスレッドをスリープ状態にします...

ただし、そうでないと主張する誤った参照がいくつかあります。状態に使用される linux.die.netsleep、プロセスを待機させます。

于 2012-08-11T14:01:50.367 に答える
7

関数を呼び出すスレッドだけです。

于 2012-08-11T14:01:23.753 に答える