假设我要创建 N 个线程,并且将不同的字符串传递到每个线程中。
伪代码:
for (i = 0; i < N; i++) {
strncpy(arg.str, some_new_str, sizeof(arg.str));
pthread_create(&threads[i],NULL,somefunc, (void *) &arg);
}
每个线程中arg
指向的字符串会改变吗?假设对于创建的第一个线程,some_new_str
是“hello”,对于第二个线程,它是“bye”。稍后,当我在线程 1 中打印该字符串时,该字符串是否会更改为“bye”而不是“hello”?
编辑:那么我应该为每个线程创建一个新的 arg 结构?
最佳答案
此实现并不安全。最后一个参数可能会在您没有注意到的情况下发生变化,因为 pthread_create 不会立即创建线程。它会在某个时候执行此操作,但那时您的本地参数可能已经更改。
作为示例,尝试运行以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* worker(void *arg) {
int val = *((int*)arg);
printf("% 5d", val);
return arg;
}
int main() {
pthread_t thid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
int n = 200;
int x = 0;
for(x = 0; x < n; ++x) {
pthread_create(&thid, &attr, worker, &x);
}
sleep(2);
printf("\n========\n");
}
并检查会发生什么。
由 P. Czarnik 编写的代码
关于c - pthread_create 是否从指针复制参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571404/