c65 Subj : Re: pthread problems: wake up a thread via pthread_cond_signal() To : comp.programming.threads From : ptjm Date : Mon Jan 03 2005 12:45 am In article , Guido wrote: % If someboby know a workaround or have general improvement for my code, % please write a short text ;-) % int main() [...] % return (0); Use pthread_exit() here. If you return from main(), your process will end. % } % pthread_mutex_lock(&status_lock); % work[id] = 0; % pthread_mutex_unlock(&status_lock); You've locked the wrong mutex here. % printf("read from device in seperate fifo !!!! %i\n", id); % % pthread_mutex_lock(&lock[id]); % % if(status[id] == 1){ % printf("wait %i\n", id); % pthread_cond_wait(&in_turn[id], &lock[id]); % } This is wrong. You want to wait until status[id] changes to 1. This should be done in a while loop, and you should have status_lock locked: % pthread_mutex_lock(&status_lock); % % while(status[id] == 1){ % printf("wait %i\n", id); % pthread_cond_wait(&in_turn[id], &status_lock); % } % pthread_mutex_lock(&status_lock); % work[id] = 1; % pthread_mutex_unlock(&status_lock); You need to lock lock[id] here, not status_lock. % pthread_mutex_lock(&status_lock); % status[i] = 1; % pthread_mutex_unlock(&status_lock); % % % if( status[i] == 1){ You need to have the mutex locked when you test status[i]. The question that springs into my mind is `what are you doing?' I can't be bothered to analyze this too closely, but it looks a lot like you're trying to demontrate a race condition. % while((int)work[i] != 1){ % pthread_cond_signal(&in_turn[i]); % printf("## signal to thread %i\n", i); % } This is very odd. Suppose you had a condition wait for work[i] to not be 1. Suppose you were holding the appropriate mutex here. Then you would be deadlocked. This thread would be signalling the CV over and over, holding the mutex the whole time, while the other thread would be trying to get the mutex so it could return from the CV wait. As it stands, you're repeatedly signalling the CV without any regard for the value of the variable the CV waiter is interested in. The repeated signals are still a useless waste of processor time, and I think you're still holding the mutex the CV waiter wants, although only because it's using the wrong mutex. Here are some rules of thumb: Associate shared data to mutexes. Lock the correct mutex when you do anything with the data. Associate condition variables with a predicate. Wait for the predicate to change in a while loop. Use the mutex associated with the predicate. Signal the CV when you change the predicate. Don't write code that gives different results if the threads are scheduled differently. -- Patrick TJ McPhee North York Canada ptjm@interlog.com . 0