Re: Using MIG RPC between 2 threads inside a process
Re: Using MIG RPC between 2 threads inside a process
- Subject: Re: Using MIG RPC between 2 threads inside a process
- From: Steve Checkoway <email@hidden>
- Date: Sat, 18 Sep 2004 02:01:14 -0700
I saw this a few days back and I meant to point out that this is not
the correct way to use conditions.
On Sep 16, 2004, at 1:12 AM, Dario wrote:
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
pthread_cond_init( &cond, NULL );
pthread_mutex_init( &lock, NULL );
server:
create client thread
pthread_mutex_lock( &lock );
while(true) {
pthread_cond_wait( &cond, &lock );
do something what you need
}
It should be something like this:
while (ServerShouldKeepGoing())
{
DoSomeStuff();
pthread_mutex_lock(&lock);
while (!CheckMyCondition())
pthread_cond_wait(&cond, &lock);
DoStuffRequiringMutualExclusion();
pthread_mutex_unlock(&lock);
PossiblyDoMoreStuff();
}
That inner while loop is absolutely essential. What if the reason the
condition cond had been signaled was no longer true, you do not wish to
proceed in this case. What if instead of signaling, it was broadcast
and multiple threads woke up in response to it?
client:
while( true ) {
pthread_mutex_lock( &lock );
Put some data in a global varibale or so.
pthread_cond_signal( &cond );
}
A client might or might not loop over and over but one thing you forgot
was to unlock after you signal.
pthread_mutex_lock(&lock);
DoSomeWork();
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
It might be better to signal after unlocking but since
pthread_cond_signal doesn't wake up the other threads right away, I'm
not sure it makes a difference. I'll bet someone here could say which
way is best.
Or can be resolved by using a queue structure with synchronized access
and verification (still with mutexes), I have an example if you need
it. with this code as you can see you can send only one job and the
client will block until the end of the previous on the server thread
This is usually easier to work with if you can get away with it. Some
times you find that you need to manipulate multiple data structures
atomically and this just doesn't quite work in that case.
- Steve
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden