如何传递for循环的索引作为pthread_create的参数 [英] How can I pass the index of a for loop as the argument for pthread_create

查看:103
本文介绍了如何传递for循环的索引作为pthread_create的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用for循环创建多个线程,并将索引i作为参数传递,如下所示:

I am using a for loop to create a number of threads and passing the index i as an argument as follows:

pthread_t p[count];
for (int i = 0; i < count; i++){
    pthread_create(&p[i], NULL, &somefunc, (void*)&i);
}

然后我尝试检索i的值:

Then I attempt to retrieve the value of i:

void *somefunc (void* ptr){
    int id = *(int*)ptr;
}

但是,我注意到有时候,线程中的id会有重叠的值,我怀疑这是由于for循环更新的索引导致线程能够检索到该值之前(因为我传入了指针,与之相反)值本身).有没有人有什么建议可以解决此问题而不降低for循环的速度?

However, I noticed that sometimes, id in the threads will have overlapping values which I suspect is due to the index of the for loop updating before the thread is able to retrieve the value (since I passed in the pointer, as opposed to the value itself). Does anyone have any suggestions to overcome this issue without slowing down the for loop?

谢谢

推荐答案

之所以发生这种情况,是因为一旦将指针传递给i,您现在就有多个使用相同值的线程.这会导致数据争用,因为第一个线程正在修改i,而第二个线程则期望它永远不会改变.您始终可以分配一个临时int并将其传递给线程函数.

This is happening because once you pass a pointer to i you now have multiple threads using the same value. This causes a data race because the first thread is modifying i and your second thread is expecting it to never change. You can always allocate a temporary int and pass it to the thread function.

pthread_create(&p[i], NULL, &somefunc, new int(i));

这将在动态存储(堆)中分配一个整数,并使用i的值对其进行初始化.指向新分配的整数的指针将被传递给线程函数.

This will allocate an integer in dynamic storage (heap) and initialize it with the value of i. A pointer to the newly allocated integer will then be passed to the thread function.

然后在线程函数中,可以像以前一样获取传递的值,然后删除int对象.

Then in the thread function you can take the value passed as you already do and then delete the int object.

void *somefunc (void* ptr){
    int id = *(int*)ptr;
    delete (int*)ptr;
}

[建议:避免使用C样式强制转换.]

这篇关于如何传递for循环的索引作为pthread_create的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆