Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Pthreads & Signals



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 );
}



BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org