Pthreads & Signals.
Anthony Gabrielson
agabriel at home.tzo.org
Wed Nov 17 11:02:36 EST 2004
Okay,
With the help of several I got it working and clarifed my
inderstanding on how pthreads work. So anyway I have it working and if
anyone is curious I attached it.
Thanks for all the help -
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 lock;
int main( int argc, char *argv[] )
{
pthread_t thread_recv;
int result;
lock = 1;
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(result));
exit ( 3 );
}
printf("main: wait cond\n");
while (lock == 1){
result = pthread_cond_wait( &got_data, &guard_revc );
printf("main: got cond %d\n",result);
lock = 0;
}
result = pthread_mutex_lock( &guard_revc );
printf("main: Got Mutex %d\n",result);
result = pthread_mutex_unlock( &guard_revc );
printf("main: Release Mutex %d\n",result);
result = pthread_cond_signal( &got_data );
printf("main: send cond %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_mutex_unlock( &guard_revc );
printf("thr: Release Mutex %d\n",result);
result = pthread_cond_signal( &got_data );
printf("thr: Sent Signal %d\n",result);
usleep(1);
while(lock == 0 ){
result = pthread_cond_wait( &got_data, &guard_revc );
printf("thr: Got Signal %d\n",result);
lock = 1;
}
pthread_exit( NULL );
}
More information about the Discuss
mailing list