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:

> 	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.

There are still a few serious issues with your code.  I hope I can
help clarify here:


1:  You're using perror(), so, technically, you're still using errno.

2:  This loop is wrong:

> 	while (lock ==  1){
> 		result = pthread_cond_wait( &got_data, &guard_revc );
> 		printf("main: got cond %d\n",result);
> 		lock = 0;   /* WRONG */
> 	}

The key to understand here is that pthread_cond_wait() can return
EARLY (for example, it could get interrupted).  Called in a loop, it
can also be interrupted MULTIPLE TIMES.  You don't want to set this
variable (lock) in this loop.  Ever.  Wait until after the loop is
complete.  Again, I urge you to look at my example code.  I've added
one line just to help clarify:


    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);
    some_variable = 1;              /* NEW */
    pthread_cond_signal(&cv);
    pthread_mutex_unlock(&lock);


3:  Your code still calls pthread_cond_wait() without first acquiring
    the mutex (in multiple places).  From the way that your code is
    structured, I'm guessing that you think that it is OK to acquire
    the mutex, release the mutex, and then call pthread_cond_wait().
    This is incorrect.  Please look at my example (above).

4:  On lines 42-47 your code locks and unlocks the mutex for no
    apparent reason.


Gotta go,

--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