【发布时间】:2013-01-01 00:49:48
【问题描述】:
我对互斥锁对代码段或代码段中的变量起作用感到困惑。
在下面的示例中,互斥锁将阻止两个线程同时尝试从 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);
.
.
}
【问题讨论】:
-
Mutex 仅用于保护数据。代码(除非自我修改,在这种情况下停止这样做!),本质上是线程安全的。