我有以下功能:
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
loop:
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
。在这种情况下,您还可以设置一个数组并传递元素的地址。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)