2

I am in a soup. The idea may be bad but i do need a solution.

  • I have two condition variable, say A and B.

  • Threads 1, 2 and 3 are waiting on A. Thread 4 is waiting on B.

  • B will be pthread_cond-signal() by thread 2, that is thread 4 will be signaled to wake up by thread 2.

Now, I have another thread 5 which pthread_cond_broadcasts() on condition variable A. I need all threads 1, 2 and 3 to wake up before thread 4 wakes up. That is say if thread 2 wakes up and signals on B thread 4 may wake up before thread 3 does, which is not what i want.

Any pointers will be highly appreciated.

thanks

3 Answers 3

2

You can solve this using condition variables. Instead of having Thread 4 wait just for the condition set by Thread 2, have it wait for a condition that is only set after all of Thread 1, Thread 2 and Thread 3 have done their thing:

pthread_mutex_lock(&thread4_lock);
while (!thread1_flag || !thread2_flag || !thread3_flag)
    pthread_cond_wait(&thread4_cond, &thread4_lock);
pthread_mutex_unlock(&thread4_lock);

/* Thread 4 can continue */

When Thread 1 has done its thing, it sets its part of the condition:

pthread_mutex_lock(&thread4_lock);
thread1_flag = 1;
pthread_cond_signal(&thread4_cond);
pthread_mutex_unlock(&thread4_lock);

...and likewise for Thread 2 and Thread 3. Thread 4 will only continue once all the flags have been set.

Sign up to request clarification or add additional context in comments.

2 Comments

This will work, but don't forget that thread11_flag, thread2_flag, and thread3_flag should be declared volatile, and you also need a proper memory barrier on non-x86 systems to ensure that the memory updates are visible to other processors.
@Adam Rosenfield: volatile and a barrier are not required, because those three flags are protected by the thread4_lock mutex as per the example.
1

Use a semaphore: have each of threads 1-3 post the semaphore, and have thread 4 wait on the semaphore 3 times instead of on a condition variable.

You'll want to use sem_init(3) or sem_open(3) to create the semaphore, sem_post(3) to post the semaphore, sem_wait(3) to wait on the semaphore, and then either sem_destroy(3) (if created with sem_init) or sem_close(3) and sem_unlink(3) (if created with sem_open) to destroy the semaphore.

1 Comment

@Adam...great. Let me try out nd get back
0

Consider using ZeroMQ's in-process signalling for this. ZeroMQ implements a messaging model which can be used effectively to coordinate threads, as well as for inter process or network messaging.

For more info: http://api.zeromq.org/2-1-1:zmq-inproc

Here is an example of load-balancing between threads using ZeroMQ and Java.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.