In a multi-threaded program I need to allocate shared memory based on the estimate computed in parallel by threads and then use that shared memory across all threads (after synchronization). Is there a way to do so without joining the threads and spawning new threads ?
To simplify I am trying to do as below:
I am using pthreads
library and pthread_barrier_wait
for multi-threading.
Sure, you're already on the right track with pthread_barrier_wait()
. Initialise the barrier to 16, then have the thread function do:
/* ...Work on estimated memory size... */
if (pthread_barrier_wait(&barrier) == PTHREAD_BARRIER_SERIAL_THREAD)
{
/* ...Allocate the shared memory... */
}
pthread_barrier_wait(&barrier);
/* ...Continue execution using shared memory... */
Threads will wait at the first barrier until all of them have finished, then exactly one of them will allocate the required memory, and they'll all wait at the second barrier until the memory has been successfully allocated.