通过队列动态地将工作分配给 pthreads
好的,我在将工作动态分配给队列中的 pthreads 时遇到问题。
例如,在我的代码中,我有一个如下所示的结构:
struct calc
{
double num;
double calcVal;
};
我将每个结构存储在长度为 l 的数组中,如下所示。
struct calc **calcArray;
/* then I initialize the calcArray to say length l and
fill each calc struct with a num*/
现在,根据 num,我想找到 calcVal 的值。每个 struct calc 都有不同的 num 值。
我想生成 4 个 pthreads,这很容易,但我想在开始时让
线程 0 获取 calcArray[0]
线程 1 获取 calcArray[1]
线程 2 获取 calcArray[2]
线程 3 获取 calcArray[3]
现在假设每个线程执行每个 calc 的计算所需的时间不同,
如果线程 1 先完成,它将获取 calcArray[4],
然后线程 3 完成并获取 calcArray [5] 执行
此操作,直到到达 calcArray[l] 的末尾。
我知道我可以将数组拆分为 l/4(每个线程获取四分之一的计算),但我不想这样做。相反,我想让工作像队列一样。关于如何做到这一点有什么想法吗?
Okay, so I'm having an issue with dynamically allocating work to pthreads in a queue.
For example, in my code I have a struct like below:
struct calc
{
double num;
double calcVal;
};
I store each struct in an array of length l like below.
struct calc **calcArray;
/* then I initialize the calcArray to say length l and
fill each calc struct with a num*/
Now, based on num, I want to find the value of calcVal. Each struct calc has a different value for num.
I want to spawn 4 pthreads which is easy enough but I want to make it so at the start,
thread 0 gets calcArray[0]
thread 1 gets calcArray[1]
thread 2 gets calcArray[2]
thread 3 gets calcArray[3]
Now assuming that it will take different times for each thread to do the calculations for each calc,
if thread 1 finishes first, it will then get calcArray[4]
then thread 3 finishes and gets calcArray[5] to do
and this continues until it reaches the end of calcArray[l].
I know I could just split the array into l/4 (each thread gets one quarter of the calcs) but I don't want to do this. Instead I want to make the work like a queue. Any ideas on how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以很容易地完成它,方法是创建一个包含要分配的下一个元素的索引的变量,然后用互斥体保护它。
示例:
另请参阅:POSIX 线程编程 - 互斥变量
You could accomplish it pretty easily, by creating a variable containing the index of the next element to be assigned, and then having it secured by a mutex.
Example:
See also: POSIX Threads Programming - Mutex Variables