Pthread互斥的必要性 [英] Necessity of pthread mutex

查看:163
本文介绍了Pthread互斥的必要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 int数组[100] ,我想5个线程计算所有的数组元素的总和。

I have an int array[100] and I want 5 threads to calculate the sum of all array elements.

通过其专用范围内的20个元素,每个线程迭代并总和写入到一个全球性的变量。

Each thread iterates through 20 elements within its dedicated range and writes the sum into a global sum variable.

是互斥必要吗?没有,因为所有的线程都来自独立源读取需要同步。

Is a mutex necessary here? There is no synchronization needed since all threads are reading from independent sources.

for(i=offset; i<offset+range; i++){
  // not used pthread_mutex_lock(&mutex);
  sum += array[i];
  // not used pthread_mutex_unlock(&mutex);
}

可这导致未predictable行为还是操作系统实际上处理呢?

Can this lead to unpredictable behavior or does the OS actually handle this?

它是明智的离开了在这种情况下互斥?我注意到,这些算法运行很多没有它快。

Is it advisable to leave out the mutex in this case? I've noticed that those algorithms run a lot faster without it.

推荐答案

是的,你需要同步的,因为所有的线程都在同一时间修改。这里的例子:

Yes, you need synchronization, because all thread are modifying the sum at the same time. Here's example:

您有4个元素 [A1,A2,A3,A4] 和2个线程 T1 和数组 T2 。首先让我们说 T1 获得价值 A1 并将其添加到。但它不是一个原子操作,所以他(这是0)的当前值复制到自己的局部空间,姑且称之为 t1_s ,更增加了它 A1 ,然后写和= t1_s 。但在同一时间 T2 做的一样,他获得值(即0,因为 T1 还没有它的操作)完成 t2_s ,增加了 A3 ,并写入。因此,我们在总和了 A3 的价值insted的的 A1 + A3 。这就是所谓的数据竞争。

You have array of 4 elements [a1, a2, a3, a4] and 2 threads t1 and t2 and sum. To begin let's say t1 get value a1 and adds it to sum. But it's not an atomic operation, so he copy current value of sum (it's 0) to his local space, let's call it t1_s, adds to it a1 and then write sum = t1_s. But at the same time t2 do the same, he get sum value (which is 0, because t1 have not completed it operation) to t2_s, adds a3 and write to sum. So we got in the sum value of a3 insted of a1 + a3. This is called data race.

有这种多种解决方案是:

There are multiple solutions to this is:


  1. 您可以使用互斥因为你已经在你的code做了,但是你提到它可能会很慢,因为互斥锁是昂贵的,所有其它线程等着吧。

  2. 创建阵列(线程数的大小),calculte所有线程本地资金,然后做这个数组中的一个线程上的最后一个减少。没有同步必要的。

  3. 无阵列计算本地 sum_local 为每个线程,并在结尾处添加所有这些款项共享变量使用互斥。我想这会更快(但它需要检查)。

  1. You can use mutex as you already did in your code, but as you mentioned it can be slow, since mutex locks are expensive and all other threads are waiting for it.
  2. Create array (with size of number of threads) to calculte local sums for all threads and then do the last reduction on this array in the one thread. No synchronization needed.
  3. Without array calculate local sum_local for each thread and in the end add all these sums to shared variable sum using mutex. I guess it will be faster (however it need to be checked).

然而,由于@gavinb提到它的所有意义只为更大的数据量。

However as @gavinb mentioned all of it make sense only for larger amount of data.

这篇关于Pthread互斥的必要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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