c - For循环的索引作为Pthread中的参数
问题描述
我和这个问题在这里有同样的问题。但是,我使用的是 C,而不是 C++,并且无法遵循公认的解决方案。我尝试过使用第二种解决方案,但这也不起作用。有什么方法可以传递循环变量的值而不是 C 中的变量本身?
解决方案
相当于您的c
链接问题的内容稍微多一些。
为了防止竞争条件(我们正在与递增的主线程竞争i
),我们不能简单地这样做:
pthread_create(&p[i],NULL,somefunc,(void *) &i);
所以,我们需要做什么new
,但是在c
. 因此,我们使用malloc
(并且线程函数应该这样做free
):
#include <pthread.h>
#include <stdlib.h>
void *
somefunc(void *ptr)
{
int id = *(int*) ptr;
// main thread _could_ free this after pthread_join, but it would need to
// remember it -- easier to do it here
free(ptr);
// do stuff ...
return (void *) 0;
}
int
main(void)
{
int count = 10;
pthread_t p[count];
for (int i = 0; i < count; i++) {
int *ptr = malloc(sizeof(int));
*ptr = i;
pthread_create(&p[i],NULL,somefunc,ptr);
}
for (int i = 0; i < count; i++)
pthread_join(p[i],NULL);
return 0;
}
推荐阅读
- javascript - JavaScript 如何计算 18 位小数的字符串值
- excel - 使用 Excel VBA 在本地 windows 文件夹中将电子邮件另存为 .msg
- python - 如何在 python 中匹配文本并制作制表符分隔表?
- javascript - Javascript querySelectorAll 数据属性值不等于
- sql - SQL:组合一张表的计数
- sass - 在伪元素的内容中使用 &
- authentication - OpenID Connect - 使用 OpenID Provider 对现有帐户系统进行身份验证
- ios - -[UINavigationController popToViewController:transition:] 中的断言失败
- javascript - 当脚本是从加载的脚本动态创建的 DOM 节点时,脚本 onload 和 window.onload 的顺序是否明确定义?
- javascript - 反应:onClick 不在 div 上呈现