gpt4 book ai didi

c - 避免与 pthread 的内存冲突

转载 作者:行者123 更新时间:2023-11-30 16:26:09 25 4
gpt4 key购买 nike

我是 pthreads 的新手,我试图了解在使用并发线程写入相同的全局变量时可以采取哪些措施来避免出现问题。这是最简单的示例:

pthread_t tid1, tid2 ;

int sum = 0 ;

void process()
{
for (int i ; i<100; i++)
sum += 1 ;
}

int main()
{

pthread_create(&tid1, NULL, (void *) process, NULL ) ;
pthread_create(&tid2, NULL, (void *) process, NULL ) ;

pthread_join(tid1, NULL) ;
pthread_join(tid2, NULL) ;

printf("Sum = %d\n", sum) ;
}

当我执行这段代码时,它有时会打印 200,有时会打印 100,这意味着在后一种情况下,我假设两个线程都试图同时写入“sum”,并且一个线程被阻塞。

在我的实际应用程序中,“sum”可能是一个大型数组,一个线程可能尝试更新一个元素,而另一个线程通常尝试更新同一数组的不同元素。

确保全局变量或数组上的所有预期读/写操作成功或至少验证操作是否成功的最简单/最干净的方法是什么?没有必要保留操作顺序。

最佳答案

我似乎找到了答案——我以前并不知道互斥体,直到在回答另一个问题时提到它:

pthread_t tid1, tid2 ;
pthread_mutex_t lock;

int sum = 0 ;

void process()
{
for (int i ; i<100; i++) {
pthread_mutex_lock(&lock);
sum += 1 ;
pthread_mutex_unlock(&lock);
}
}

int main()
{
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}

pthread_create(&tid1, NULL, (void *) process, NULL ) ;
pthread_create(&tid2, NULL, (void *) process, NULL ) ;

pthread_join(tid1, NULL) ;
pthread_join(tid2, NULL) ;

pthread_mutex_destroy(&lock);

printf("Sum = %d\n", sum) ;
}

关于c - 避免与 pthread 的内存冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53148257/

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