How to synchronize manager/worker pthreads without a join?

后端 未结 4 1638
后悔当初
后悔当初 2021-02-01 10:28

I\'m familiar with multithreading and I\'ve developed many multithreaded programs in Java and Objective-C successfully. But I couldn\'t achieve the following in C using pthreads

4条回答
  •  深忆病人
    2021-02-01 10:38

    You need to use a different synchronization technique than join, that's clear.

    Unfortunately you have a lot of options. One is a "synchronization barrier", which basically is a thing where each thread that reaches it blocks until they've all reached it (you specify the number of threads in advance). Look at pthread_barrier.

    Another is to use a condition-variable/mutex pair (pthread_cond_*). When each thread finishes it takes the mutex, increments a count, signals the condvar. The main thread waits on the condvar until the count reaches the value it expects. The code looks like this:

    // thread has finished
    mutex_lock
    ++global_count
    // optional optimization: only execute the next line when global_count >= N
    cond_signal
    mutex_unlock
    
    // main is waiting for N threads to finish
    mutex_lock
    while (global_count < N) {
        cond_wait
    }
    mutex_unlock
    

    Another is to use a semaphore per thread -- when the thread finishes it posts its own semaphore, and the main thread waits on each semaphore in turn instead of joining each thread in turn.

    You also need synchronization to re-start the threads for the next job -- this could be a second synchronization object of the same type as the first, with details changed for the fact that you have 1 poster and N waiters rather than the other way around. Or you could (with care) re-use the same object for both purposes.

    If you've tried these things and your code didn't work, maybe ask a new specific question about the code you tried. All of them are adequate to the task.

提交回复
热议问题