C pthread同步功能

Fre*_*ong 13 c synchronization pthreads

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

function thread_worker(){
    //hard working

    syncThreads();
    printf("all threads are sync\n");
}
Run Code Online (Sandbox Code Playgroud)

因此只有当所有线程结束艰苦工作时才会调用printf.

nne*_*neo 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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 就像我说的,你可以重用屏障.从`man pthread_barrier_wait`:'[当`pthread_barrier_wait`返回]时,屏障应该被重置为它最近引用它的pthread_barrier_init()函数所具有的状态. (4认同)