gpt4 book ai didi

C - 线程的并发问题,参数被打印两次

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:48 25 4
gpt4 key购买 nike

我编写的这个程序应该在主循环的每次迭代中创建一个新线程,并让它打印迭代变量。例如。在第一次迭代中,创建了一个新线程,它应该打印“arg: 0”,下一次迭代打印“arg: 1”等。

正如您在下面的屏幕截图中看到的,arg 3 和 7 被打印了两次,而它应该只打印一次。现在,如果我将 sleep(1) 添加到每次迭代,它就可以工作,所以这是某种并发问题。请注意,每次的结果都是完全随机的,而不仅仅是每次的 3 和 7。

有人有想法吗?谢谢!

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

static void * mutex_thread(void * arg);
int threads_amt = 10;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main (void)
{
pthread_t threads[threads_amt];

// Create threads.
for(int i = 0; i < threads_amt; i++)
{
printf ("Starting thread [%d]...\n", i);

// Create thread.
pthread_create (&threads[i], NULL, mutex_thread, &i);

// IT WORKS IF I ENABLE sleep(1).
//sleep (1);

printf ("Thread created.\n\n");
}

// Join threads.
printf("Joining threads...\n");
for(int i = 0; i < threads_amt; i++)
{
pthread_join (threads[i], NULL);
}

return (0);
}

static void * mutex_thread(void * arg)
{
// Lock mutex.
pthread_mutex_lock (&mutex);

// Print arg.
int *number = (int*)arg;
printf("arg: %d\n", *number);

// Unlock mutex.
pthread_mutex_unlock (&mutex);

return (NULL);
}

result

最佳答案

你有data race - 因为您将(变量 i 的)相同地址传递给所有线程。

向每个线程传递不同的地址(例如使用数组或使用“malloc”值)。

关于C - 线程的并发问题,参数被打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46512278/

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