我有以下功能:
void *foo(void *i) {
int a = (int) i;
}
int main() {
pthread_t thread;
int i;
pthread_create(&thread, 0, foo, (void *) i);
}
在编译时,有一些关于转换的错误((void *) i
and 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/19232957/