gpt4 book ai didi

c - 为什么我不能将我的 "for"索引直接传递给 pthread_create 调用?

转载 作者:太空狗 更新时间:2023-10-29 15:56:30 26 4
gpt4 key购买 nike

#define THREADS_NUMBER 10

给定一个函数f:

void *f(void *arg){

pthread_mutex_lock(&mutex);
printf("%i\n", *((int*) arg);
pthread_mutex_unlock(&mutex);

}

我不明白为什么要写这个:

pthread_t threads[THREADS_NUMBER];
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_create(&threads[i], NULL, f, &i);
}
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_join(threads[i], NULL);
}

输出这个:

2 4 4 5 5 6 8 8 9 10

写这篇文章时:

int t[10];
for(int i = 0; i < 10; i++)
t[i] = i;
pthread_t threads[THREADS_NUMBER];
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_create(&threads[i], NULL, f, &t[i]);
}
for(int i = 0; i < THREADS_NUMBER; i++){
pthread_join(threads[i], NULL);
}

输出这个:

0 1 4 3 5 2 6 7 9 8

(如果您没有注意到差异,它是在 pthread_create 调用中传递给线程函数 f 的参数。)

最佳答案

尝试展开循环。这两种情况将变成如下。

第一种情况:

pthread_create(&threads[0], NULL, f, &i);
pthread_create(&threads[1], NULL, f, &i);


pthread_create(&threads[9], NULL, f, &i);

第二种情况:

pthread_create(&threads[0], NULL, f, &t[0]);
pthread_create(&threads[0], NULL, f, &t[1]);

pthread_create(&threads[9], NULL, f, &t[9]);

如果您注意到,在第一种情况下,您总是将 &i 传递给每个线程,因此每个线程都将指向相同的 i 及其最新内容。

关于c - 为什么我不能将我的 "for"索引直接传递给 pthread_create 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58341303/

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