2014-03-04 53 views
1

我遇到以下代碼的一些問題。我似乎無法找到該錯誤:有關POSIX線程上的互斥鎖的問題

 1 #include <pthread.h> 
    2 #include <stdio.h> 
    3 #include <stdlib.h> 
    4 #include <unistd.h> 
    5 
    6 struct bla 
    7 { 
    8  pthread_mutex_t mut; 
    9  int x; 
    10 }; 
    11 
    12 
    13 pthread_t tid; 
    14 
    15 void *thr_fn1 (struct bla *fp); 
    16 
    17 int main() 
    18 { 
    19  struct bla *fp; 
    20  fp = (struct bla *) malloc (sizeof(struct bla)); 
    21  fp->x=3; 
    22  printf ("Initializing mutex_init\n"); 
    23  pthread_mutex_init (&fp->mut,NULL); 
    24  pthread_create (&tid,NULL,thr_fn1,fp); 
    25  sleep (2); 
    26  printf ("Main thread ended sleep. Incrementing.\n"); 
    27  fp->x++; 
    28  pthread_join (tid,NULL); 
    29  printf ("x=%d\n",fp->x); 
    30  pthread_mutex_destroy(&fp->mut); 
    31  return 0; 
    32 
    33 } 
    34 
    35 void *thr_fn1 (struct bla *fp) 
    36 { 
    37  printf ("Locking new thread!\n"); 
    38  pthread_mutex_lock (&fp->mut); 
    39  printf ("Sleeping.\n"); 
    40  sleep (5); 
    41  pthread_mutex_unlock (&fp->mut); 
    42  printf ("Thread unlocked.\n"); 
    43  return ((void *) 0); 
    44 } 

爲什麼值仍然在第27行增加?它不應該被第二個線程中的互斥鎖保護(第38行)嗎?

謝謝!

+0

的互斥是如何工作的有趣的誤會。 – alk

回答

2

互斥體和數據之間沒有自動關聯。如果你想有一個互斥量,以保護一些特定的數據集,負責鎖定和解鎖互斥各地訪問這些數據:

sleep (2); 
pthread_mutex_lock(&fp->mut); 
printf ("Main thread ended sleep. Incrementing.\n"); 
fp->x++; 
pthread_mutex_unlock(&fp->mut);