我有以下功能:
void *foo(void *i) {
int a = (int) i;
}
int main() {
pthread_t thread;
int i;
pthread_create(&thread, 0, foo, (void *) i);
}
编译时,有关转换(
(void *) i
和int a = (int) i
)存在一些错误。如何正确传递整数作为pthread_create
的最后一个参数? 最佳答案
基于szx的答案(因此请给他功劳),这是它在您的for
循环中如何工作的:
void *foo(void *i) {
int a = *((int *) i);
free(i);
}
int main() {
pthread_t thread;
for ( int i = 0; i < 10; ++1 ) {
int *arg = malloc(sizeof(*arg));
if ( arg == NULL ) {
fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
exit(EXIT_FAILURE);
}
*arg = i;
pthread_create(&thread, 0, foo, arg);
}
/* Wait for threads, etc */
return 0;
}
在循环的每次迭代中,您都在分配新的内存,每个内存具有不同的地址,因此在每次迭代中传递给
pthread_create()
的东西都是不同的,因此没有线程最终会尝试访问相同的内存,并且您不会像通过传递i
的地址那样遇到任何线程安全问题。在这种情况下,您还可以设置一个数组并传递元素的地址。关于c - pthread_create并传递一个整数作为最后一个参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55601282/