Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pthread synchronize function

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

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

like image 408
Frederico Schardong Avatar asked Oct 16 '12 04:10

Frederico Schardong


People also ask

How do I sync pthreads?

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.

What is thread synchronization in C?

Prerequisite : Multithreading in C. Thread synchronization is defined as a mechanism which ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segment known as a critical section.

How does thread synchronize?

Thread synchronization is the concurrent execution of two or more threads that share critical resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.

What is POSIX synchronization?

1.0 POSIX Threads SynchronizationPOSIX Threads provide multiple flows of execution within a process. The threads have their own stacks but share the global data and the heap. So the global variables are visible to multiple threads.


1 Answers

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.

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
    }
}
like image 96
nneonneo Avatar answered Sep 18 '22 23:09

nneonneo