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



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




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