c中的互斥锁和线程
Mutex and thread in c
我有这个代码:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
int cont = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void* codiceThreadIncremento(void *arg)
{
//sezione critica
pthread_mutex_lock(&mut);
printf("hello");
cont++;
pthread_mutex_unlock(&mut);
return NULL;
}
int main(void){
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, &codiceThreadIncremento,NULL);
printf("valore cont1 %d \n",cont);
pthread_create(&thread2, NULL, &codiceThreadIncremento, NULL);
printf("valore cont2 %d \n",cont);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
pthread_mutex_destroy(&mut);
return 0;
}
我想尝试使用互斥量简单地增加变量“cont
”。
当我执行这段代码时,我得到了这个:
valore cont1 0
valore cont2 0
但我希望
valore cont1= 1
valore con2 = 2
在您调用 pthread_join
之前,线程不一定 运行。
那时你已经打印了输出。
I expect valore cont1= 1 valore con2 = 2"
您不能对这个程序有任何期望。在一个或多个线程中修改变量时,您正在访问 main
中的变量。这是一场数据竞赛和未定义的行为。
即使您在 main
中添加了互斥锁保护,您也不能指望在打印值之前发生增量。线程的全部意义在于它们是异步执行的。如果你想要同步增量,不要使用线程。
我有这个代码:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
int cont = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void* codiceThreadIncremento(void *arg)
{
//sezione critica
pthread_mutex_lock(&mut);
printf("hello");
cont++;
pthread_mutex_unlock(&mut);
return NULL;
}
int main(void){
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, &codiceThreadIncremento,NULL);
printf("valore cont1 %d \n",cont);
pthread_create(&thread2, NULL, &codiceThreadIncremento, NULL);
printf("valore cont2 %d \n",cont);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
pthread_mutex_destroy(&mut);
return 0;
}
我想尝试使用互斥量简单地增加变量“cont
”。
当我执行这段代码时,我得到了这个:
valore cont1 0
valore cont2 0
但我希望
valore cont1= 1
valore con2 = 2
在您调用 pthread_join
之前,线程不一定 运行。
那时你已经打印了输出。
I expect valore cont1= 1 valore con2 = 2"
您不能对这个程序有任何期望。在一个或多个线程中修改变量时,您正在访问 main
中的变量。这是一场数据竞赛和未定义的行为。
即使您在 main
中添加了互斥锁保护,您也不能指望在打印值之前发生增量。线程的全部意义在于它们是异步执行的。如果你想要同步增量,不要使用线程。