Pthreads & Signals
Kevin D. Clark
clark_k at pannaway.com
Wed Nov 17 09:42:38 EST 2004
Anthony Gabrielson <agabriel at home.tzo.org> writes:
> Any more ideas?
I have a couple.
1: errno isn't set by any of the pthread_ functions (at least, none
that I can think of). So, your code like this is wrong:
: result = pthread_create(&thread_recv, NULL,
: thr, NULL );
:
: if ( result != 0 ) {
: perror( "pthread_create failed" );
: printf( "%s\n",strerror(errno));
This is correct:
: result = pthread_create(&thread_recv, NULL,
: thr, NULL );
:
: if ( result != 0 ) {
: printf("pthread_create failed: %s\n", strerror(result));
2: You're calling pthread_cond_wait() without first locking the mutex
that you're using.
3: You're calling pthread_cond_wait() without enclosing this call in
a loop. This is nearly always wrong.
Regarding (2) and (3) your code should look more like this:
pthread_mutex_t lock;
pthread_cond_t cv;
int some_variable = 0;
/* HERE IS THE CODE TO WAIT */
pthread_mutex_lock(&lock);
while (some_variable == 0) {
pthread_cond_wait(&lock, &cv);
}
/* mutex is reacquired at this point */
do_some_stuff();
pthread_mutex_unlock(&lock);
...
/* HERE IS THE CODE TO SIGNAL */
pthread_mutex_lock(&lock);
pthread_cond_signal(&cv);
pthread_mutex_unlock(&lock);
Don't take the following statement the wrong way (I'm trying to be
impassive and clinical here): Just because your code "works" on
several other platforms doesn't mean that it is correct.
Incorrect code will bite you hard at some point.
Hope this helps,
--kevin
--
GnuPG ID: B280F24E And the madness of the crowd
Is an epileptic fit
-- Tom Waits
More information about the Discuss
mailing list