我对互斥锁适用于代码段或代码段中的变量感到困惑。
在下面的示例中,互斥锁将阻止两个线程同时尝试从 func1 或 func2 访问 mysum,或者仅保护互斥锁锁定和解锁之间的代码段
.
.
pthread_mutex_t myMutex;
int mysum;
void func1(){
.
.
.
pthread_mutex_lock (&myMutex);
mysum--;
printf("Thread %ld did mysum=%d\n",id,mysum);
pthread_mutex_unlock (&myMutex);
.
.
}
void func2(){
.
.
.
mysum++;
pthread_mutex_lock (&myMutex);
mysum++;
printf("Thread %ld did mysum=%d\n",id,mysum);
pthread_mutex_unlock (&myMutex);
.
.
}
int main (int argc, char *argv[])
{
pthread_mutex_init(&myMutex, NULL);
.
.
pthread_create(&callThd1, &attr, func1, NULL);
pthread_create(&callThd2, &attr, func2, NULL);
pthread_create(&callThd3, &attr, func1, NULL);
pthread_create(&callThd4, &attr, func2, NULL);
pthread_create(&callThd5, &attr, func1, NULL);
pthread_create(&callThd6, &attr, func2, NULL);
.
.
pthread_mutex_destroy(&myMutex);
.
.
}