C pthread同步函数 [英] C pthread synchronize function

查看:40
本文介绍了C pthread同步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a function in pthread library to synchronize threads? 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. E.g:

function thread_worker(){
    //hard working

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

所以只有当所有线程结束努力工作时才调用 printf.

So the printf is called only when all the threads end the hard working.

推荐答案

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

The proper way to do this would be with a barrier. pthread supports barriers using 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_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
    }
}

这篇关于C pthread同步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆