日期:2014-05-16  浏览次数:20627 次

关于互斥访问共享变量的问题(菜鸟求高手)
会的话应该很简单吧!程序中的两个线程各自把counter加5次,但不知道为什么(val+1)总是1的?求解惑求解答

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

#define NLOOP 5

int counter;/*incremented by threads*/

pthread_mutex_t work_mutex;

void * increase(void * vptr);
int main(int argc,char** argv)
{
pthread_t threadIdA,threadIdB;
if(pthread_mutex_init(&work_mutex,NULL)!=0){
perror("Mutex init failed");
exit(1);
}
pthread_create(&threadIdA,NULL,&increase,NULL);
pthread_create(&threadIdB,NULL,&increase,NULL);

/*wait for both threads to terminate*/
pthread_join(threadIdA,NULL);
pthread_join(threadIdB,NULL);
pthread_mutex_destroy(&work_mutex);
return 0;
}

void* increase(void *vptr)
{
  int i,val;
  if(pthread_mutex_lock(&work_mutex)!=0){
  perror("Lock failed");
  exit(1);
  }
for(i=0;i<NLOOP;i++){
val=counter;
printf("jj %d\n",val);
printf("%x: %d\n",(unsigned int)pthread_self(),val+1);
}
if(pthread_mutex_unlock(&work_mutex)!=0){
perror("unlock failed");
exit(1);
}
else
printf("success unlock\n");
return NULL;
}

------解决方案--------------------
你说呢?

val = counter;

请问counter变过吗?

printf("%x: %d\n",(unsigned int)pthread_self(),val+1);

请问val+1变过吗?