当前位置: 技术问答>linux和unix
关于互斥访问共享变量的问题(菜鸟求高手)
来源: 互联网 发布时间:2017-02-26
本文导语: 会的话应该很简单吧!程序中的两个线程各自把counter加5次,但不知道为什么(val+1)总是1的?求解惑求解答 #include #include #include #define NLOOP 5 int counter;/*incremented by threads*/ pthread_mutex_t work_mutex; void * increase(void ...
会的话应该很简单吧!程序中的两个线程各自把counter加5次,但不知道为什么(val+1)总是1的?求解惑求解答
#include
#include
#include
#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
#include
#include
#include
#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