13

pthread 库中是否有同步线程的函数?不是互斥锁,不是信号量,只是一个调用函数。它应该锁定进入该点的线程,直到所有线程都达到这样的功能。例如:

function thread_worker(){
    //hard working

    syncThreads();
    printf("all threads are sync\n");
}

所以 printf 仅在所有线程结束辛勤工作时才被调用。

4

1 回答 1

19

正确的方法是使用屏障pthread支持使用pthread_barrier_t. 您使用需要同步的线程数对其进行初始化,然后您只需使用pthread_barrier_wait这些线程即可同步。

例子:

pthread_barrier_t barr;

void thread_worker() {
    // do work
    // now make all the threads sync up
    int res = pthread_barrier_wait(&barr);
    if(res == PTHREAD_BARRIER_SERIAL_THREAD) {
        // this is the unique "serial thread"; you can e.g. combine some results here
    } else if(res != 0) {
        // error occurred
    } else {
        // non-serial thread released
    }
}


int main() {
    int nthreads = 5;
    pthread_barrier_init(&barr, NULL, nthreads);

    int i;
    for(i=0; i<nthreads; i++) {
        // create threads
    }
}
于 2012-10-16T04:29:28.973 回答