Pthreads & Signals
Anthony Gabrielson
agabriel at home.tzo.org
Wed Nov 17 09:22:30 EST 2004
Jerry,
I think I actually had a mutex unlock in main without ever locking
it. If I take that out, the code breaks again. So with a few questions
out I learned that I need to have the Mutex to properly send a signal,
otherwise results are unpredictable. So thats fine I'll take the mutex
after the condition is met, I'll resend the signal and releast the mutex
so the thread can get it. Well, this works reliable everywhere I can test
except linux (FC2); I have tested this code on OpenBSD, Cygwin, and SFU
3.5 and it *always* works. Under Linux however it only works ever third
time or so...
Any more ideas?
Thanks,
Anthony
-------------- next part --------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
pthread_mutex_t guard_revc;
pthread_cond_t got_data;
void *thr(void *);
int main( int argc, char *argv[] )
{
pthread_t thread_recv;
int result;
pthread_cond_init( &got_data, NULL );
pthread_mutex_init( &guard_revc, NULL );
result = pthread_create(&thread_recv, NULL,
thr, NULL );
if ( result != 0 ) {
perror( "pthread_create failed" );
printf( "%s\n",strerror(errno));
exit ( 3 );
}
printf("main: wait cond\n");
result = pthread_cond_wait( &got_data, &guard_revc );
printf("main: got cond %d\n",result);
result = pthread_mutex_lock( &guard_revc );
printf("main: Got Mutex %d\n",result);
result = pthread_cond_signal( &got_data );
printf("main: send cond %d\n",result);
result = pthread_mutex_unlock( &guard_revc );
printf("main: Release Mutex %d\n",result);
usleep(1);
pthread_join(thread_recv,NULL);
return 0;
}
void *thr( void *arg ){
int result;
result = pthread_mutex_lock( &guard_revc );
printf("thr: Got Mutex %d\n",result);
usleep(1);
result = pthread_cond_signal( &got_data );
printf("thr: Sent Signal %d\n",result);
result = pthread_mutex_unlock( &guard_revc );
printf("thr: Release Mutex %d\n",result);
usleep(1);
result = pthread_cond_wait( &got_data, &guard_revc );
printf("thr: Got Signal %d\n",result);
pthread_exit( NULL );
}
More information about the Discuss
mailing list