gpt4 book ai didi

c - 对 pthread 使用互斥会导致随机答案

转载 作者:行者123 更新时间:2023-12-01 07:43:57 25 4
gpt4 key购买 nike

我写了一个简单的pthread代码,它

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

#define ITERATIONS 500

// A shared mutex
pthread_mutex_t mutex;
int target;

void* opponent(void *arg)
{
int i;
printf("opp, before for target=%d\n", target);
pthread_mutex_lock(&mutex);
for(i = 0; i < ITERATIONS; ++i)
{
target++;
}
pthread_mutex_unlock(&mutex);
printf("opp, after for target=%d\n", target);

return NULL;
}

int main(int argc, char **argv)
{
pthread_t other;

target = 5;

// Initialize the mutex
if(pthread_mutex_init(&mutex, NULL))
{
printf("Unable to initialize a mutex\n");
return -1;
}

if(pthread_create(&other, NULL, &opponent, NULL))
{
printf("Unable to spawn thread\n");
return -1;
}

int i;
printf("main, before for target=%d\n", target);
pthread_mutex_lock(&mutex);
for(i = 0; i < ITERATIONS; ++i)
{
target--;
}
pthread_mutex_unlock(&mutex);
printf("main, after for target=%d\n", target);

if(pthread_join(other, NULL))
{
printf("Could not join thread\n");
return -1;
}

// Clean up the mutex
pthread_mutex_destroy(&mutex);

printf("Result: %d\n", target);

return 0;
}

然后我用这个命令编译

gcc -pedantic -Wall -o theaded_program pth.c -lpthread

但是,每次运行程序时,我都会得到不同的结果!!

 $ ./theaded_program
main, before for target=5
main, after for target=-495
opp, before for target=5
opp, after for target=5
Result: 5

$ ./theaded_program
main, before for target=5
opp, before for target=5
opp, after for target=5
main, after for target=-495
Result: 5

最佳答案

printf() 语句在互斥量被锁定且访问target 时不执行:

printf("opp, before for target=%d\n", target);
pthread_mutex_lock(&mutex);

这意味着一个线程可能正在更改 target 的值,而另一个线程正在尝试读取它(在 printf() 中)。将互斥锁锁定时要执行的 printf() 语句移动到:

pthread_mutex_lock(&mutex);
printf("opp, before for target=%d\n", target);
/* snip */
printf("opp, after for target=%d\n", target);
pthread_mutex_unlock(&mutex);

这将防止 target 被一个线程读取并同时被另一个线程修改。但是,无法保证哪个线程将首先获取互斥量。

关于c - 对 pthread 使用互斥会导致随机答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15811605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com