写这个东西完全是初级的东西,给不理解的人看的,理解了请pass...
1.源代码:
#include <stdio.h>
#include <pthread.h>
int critical_var =0;
pthread_mutex_t mutex_c= PTHREAD_MUTEX_INITIALIZER;
void* printf_fn(void *data)
{
int critical_var_bak=pthread_self();
while(1){
//pthread_mutex_lock(&mutex_c);
critical_var = critical_var_bak;
sleep(1);
if(critical_var != critical_var_bak){
printf("found ...\n");
printf("tid:%d critical:%d\n",critical_var_bak,critical_var);
}
//pthread_mutex_unlock(&mutex_c);
}
return (void*)NULL;
}
int main()
{
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,printf_fn,NULL);
pthread_create(&tid2,NULL,printf_fn,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
2.编译运行
gcc pthread_test.c -o pthread_test -g -lpthread
打印:
found ...
tid:-1328888064 critical:-1337280768
found ...
tid:-1337280768 critical:-1328888064
found ...
tid:-1328888064 critical:-1337280768
found ...
tid:-1337280768 critical:-1328888064
found ...
tid:-1328888064 critical:-1337280768
found ...
tid:-1337280768 critical:-1328888064
很明显的可以看出来 critial的变量在线程切换的时候改变了状态。
- 如果打开互斥锁(//pthread_mutex_lock(&mutex_c);),就完全可以避免了此类问题。改一下 printf_fn
void* printf_fn(void *data)
{
int critical_var_bak=pthread_self();
while(1){
pthread_mutex_lock(&mutex_c);
critical_var = critical_var_bak;
sleep(1);
if(critical_var != critical_var_bak){
printf("found ...\n");
printf("tid:%d critical:%d\n",critical_var_bak,critical_var);
}
pthread_mutex_unlock(&mutex_c);
}
return (void*)NULL;
}
4.重新编译运行
5.结果没有critical的打印了。
网友评论