multithreaded programming

specifically using pthread.h
Do I need to lock the mutex each time a shared variable is used to check a condition in for example an if or while statement?

For example, if x is the shared variable of datatype int,
1
2
3
4
5
6
7
8
9
10
11

pthread_mutex_lock( &lock );
while ( x )
{
    // Do something with x
    pthread_mutex_unlock( &lock )
    // Do something that does not involve x
    pthread_mutex_lock( &lock );
}
pthread_mutex_unlock( &lock )
Last edited on
Yes, although it's probably smarter to just copy the data elsewhere first.
Topic archived. No new replies allowed.