对pthread

编程入门 行业动态 更新时间:2024-10-28 11:26:02
本文介绍了对pthread_create()中的参数感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题:为什么不将& i作为最后一个参数传递给pthread_create()?相反,他创建了一个数组来保存相同的东西....

My question :why not just pass &i as the last argument to pthread_create()? instead he create a array to hold the same thing....

#define THREAD_CT 2 /* bump this up a few numbers if you like */ void *print_stuff(void *ptr) { int i, id= * (int *) ptr; for (i= 0; i < 5; i++) { printf("Thread %d, loop %d.\n", id, i); sleep(rand() % 2); /* sleep 0 or 1 seconds */ } printf("Thread %d exiting.\n", id); return NULL; } int main(void) { pthread_t tids[THREAD_CT]; int i, ids[THREAD_CT]; for (i= 0; i < THREAD_CT; i++) { ids[i]= i; pthread_create(&tids[i], NULL, print_stuff, &ids[i]); printf("Main thread created thread %d (ID %ld).\n", i, tids[i]); } for (i= 0; i < THREAD_CT; i++) { pthread_join(tids[i], NULL); printf("Main thread reaped thread %d (ID %ld).\n", i, tids[i]); } return 0; }

推荐答案

为什么不将& i作为最后一个参数传递给pthread_create()?

why not just pass &i as the last argument to pthread_create()?

因为这样做,所有线程将共享地址i,并且线程之间将发生数据争用.

Because if you do that all threads will share the address i and there will be data race between threads.

另一种方法是将值强制转换为:

The alternative is to cast the value like:

pthread_create(&tids[i], NULL, print_stuff, (void *)i);

但是这个整数到指针的转换具有实现定义的行为.所以现在拥有它可能是最好的方法

But this integer to pointer conversion has implementation-defined behaviour. So the way you have it now is probably the best way

还请注意,rand()不是线程安全的.

Also note that rand() is not thread-safe.

更多推荐

对pthread

本文发布于:2023-10-09 02:06:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pthread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!