On Tue, 25 May 2004, Bryan O'Donoghue wrote:
>> > I'm not sure I understand: is the problem that thread 1 might update twice
> > and at least one of threads 2 to n might miss a transition?
>> The problem is that thread 2: can send data before or after thread 1 has
> executed. A race condition I guess you'd call it.
>> The pthread_cond_wait/broadcast logic assumes thread 1 to be in a wait state
> for thread 2, to signal it and wake it up.
Hmmm. You can avoid "assumptions" by getting each thread to write down
(under mutex protection) what its state is. Note that pthread_cond_wait()
explicitly allows you to atomically wait on a condition *and* release a
mutex. In other words, the thread goes into a wait state from inside
mutex protection.
> This is no good if thread 2 is finished it's execution before thread 1 has put
> itself into a wait state.
Here's one possible way round this (if I've understood correctly)
Thread 1:
a) lock mutex
b) if thread 2 is marked as finished, release mutex and don't wait.
c) otherwise, mark self as being in a wait state, and call
pthread_cond_wait (releasing mutex at the same time).
Thread 2: (before exiting)
a) lock mutex
b) if thread 1 is marked as waiting, fire pthread_cond_signal()
c) mark self as finished
d) release mutex.
The most powerful ideas here (I think) are:
1) Each thread records its own condition
2) Each thread decides (based on what it has just done and the condition
of other threads) what threads need signalling.
3) pthread_cond_wait does 2 things: thread -> waiting; release mutex
Ronan
Maintained by the ILUG website team. The aim of Linux.ie is to
support and help commercial and private users of Linux in Ireland. You can
display ILUG news in your own webpages, read backend
information to find out how. Networking services kindly provided by HEAnet, server kindly donated by
Dell. Linux is a trademark of Linus Torvalds,
used with permission. No penguins were harmed in the production or maintenance
of this highly praised website. Looking for the
Indian Linux Users' Group? Try here. If you've read all this and aren't a lawyer: you should be!