简体   繁体   English

C pthread同步功能

[英]C pthread synchronize function

Is there a function in pthread library to synchronize threads? pthread库中是否有一个函数来同步线程? Not mutexes, not semaphores, just one call function. 不是互斥体,不是信号量,只是一个调用函数。 It is supposed to lock the threads that get in that point until all the threads reach such function. 它应该锁定进入该点的线程,直到所有线程都达到这样的功能。 Eg: 例如:

function thread_worker(){
    //hard working

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

So the printf is called only when all the threads end the hard working. 因此只有当所有线程结束艰苦工作时才会调用printf。

The proper way to do this would be with a barrier . 这样做的正确方法是使用屏障 pthread supports barriers using pthread_barrier_t . pthread使用pthread_barrier_t支持障碍。 You initialize it with the number of threads that will need to sync up, and then you just use pthread_barrier_wait to make those threads sync up. 您使用需要同步的线程数初始化它,然后您只需使用pthread_barrier_wait使这些线程同步。

Example: 例:

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM