Pthreads并且互斥;阵列的锁定部 [英] Pthreads and mutexes; locking part of an array

查看:114
本文介绍了Pthreads并且互斥;阵列的锁定部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用并行的pthreads的操作。这个过程看起来是这样的:

I am trying to parallelize an operation using pthreads. The process looks something like:

double* doSomething( .... )  {   
 double* foo;   
 foo = new double[220];  

 for(i = 0; i<20; i++)  
 {  
  //do something with the elements in foo located between 10*i and 10*(i+2)  
 }  

 return foo; 
}

for循环内部发生的东西,可以以任何顺序来完成,所以我想这个组织使用线程。

The stuff happening inside the for-loop can be done in any order, so I want to organize this using threads.

有关实例,我可以使用多个线程,使得每个线程穿过for循环的部分,但适用于所述阵列的不同部分。为了避免麻烦的重叠部分工作时,我需要锁定一些内存。

For instance, I could use a number of threads such that each thread goes through parts of the for-loop, but works on different parts of the array. To avoid trouble when working on overlapping parts, i need to lock some memory.

我怎么能作出这样的锁定阵列的一部分互斥(或别的什么)?

How can I make a mutex (or something else) that locks only part of the array?

推荐答案

如果你只是想确保阵列的部分曾经工作过...

If you just want to make sure that a section of the array is worked once...

请一个全局变量:

int _iNextSection;  

当一个线程准备要上一节操作,线程获取下一个可用的部分是这样的:

Whenever a thread gets ready to operate on a section, the thread gets the next available section this way:

iMySection = __sync_fetch_and_add(&_iNextSection, 1);

__sync_fetch_and_add()返回当前_iNextSection的值,然后递增_iNextSection。 __sync_fetch_and_add()是原子,这意味着__sync_fetch_and_add()是保证完成之前,另一个线程可以做到这一点。没有锁定,不堵,简单,快速。

__sync_fetch_and_add() returns the current value of _iNextSection and then increments _iNextSection. __sync_fetch_and_add() is atomic, which means __sync_fetch_and_add() is guaranteed to complete before another thread can do it. No locking, no blocking, simple, fast.

这篇关于Pthreads并且互斥;阵列的锁定部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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