[英]Can someone explain this code's logic to me?
I was practicing multithreading and looking for problems online.我正在练习多线程并在网上寻找问题。 But i cannot understand the logic behind this chunk of code.
但我无法理解这段代码背后的逻辑。
The code creates 4 threads and sums the 1/4th part of the array.该代码创建了 4 个线程并对数组的 1/4 部分求和。 I know how to create threads but cannot understand the sum function.
我知道如何创建线程,但无法理解总和 function。
#include <pthread.h>
#include <stdio.h>
// size of array
#define MAX 100
// maximum number of threads
#define MAX_THREAD 4
int fill_array[100];
int sum[4] = { 0 };
int part = 0;
void* sum_array(void* arg)
{
int i=0;
// Each thread computes sum of 1/4th of array
int thread_part = part++;
for ( i = thread_part * (MAX / 4); i < (thread_part + 1) * (MAX / 4); i++)
sum[thread_part] += fill_array[i];
}
Each time sum_array
is called, the elements thread_part * (MAX / 4)
(inclusive) to (thread_part + 1) * (MAX / 4)
(exclusive) are summed.每次调用
sum_array
时,都会对元素thread_part * (MAX / 4)
(包括)到(thread_part + 1) * (MAX / 4)
(不包括)求和。
sum_array
is called, thread_part
is 0
, and sum_array
will sum elements [0,25) into sum[0]
.sum_array
, thread_part
为0
, sum_array
将元素 [0,25) 加到sum[0]
中。sum_array
is called, thread_part
is 1
, and sum_array
will sum elements [25,50) into sum[1]
.sum_array
, thread_part
为1
, sum_array
将元素 [25,50) 加到sum[1]
中。sum_array
is called, thread_part
is 2
, and sum_array
will sum elements [50,75) into sum[2]
.thread_part
为2
, sum_array
sum_array
加到sum[2]
中。sum_array
is called, thread_part
is 3
, and sum_array
will sum elements [75,100) into sum[3]
.thread_part
为3
, sum_array
将元素 [ sum_array
) 加到sum[3]
中。 The above is true as long as the calls to sum_array
are sequential.只要对
sum_array
的调用是连续的,上述情况就成立。 However, I presume that sum_array
is being called once by each of four simultaneously-running threads.但是,我认为
sum_array
被四个同时运行的线程中的每一个调用一次。 Because part++
isn't thread-safe, thread_part
isn't guaranteed to be different in each thread, so it won't work as nicely as described above.因为
part++
不是线程安全的, thread_part
不能保证在每个线程中都不同,所以它不会像上面描述的那样工作得那么好。
To achieve the desired result, you need to make part++
atomic (eg using a lock).要达到预期的结果,您需要使
part++
原子化(例如使用锁)。 Better yet, pass thread_part
as an argument to the thread.更好的是,将
thread_part
作为参数传递给线程。
Note that MAX
must be evenly divisible by 4
or elements won't be summed.请注意,
MAX
必须能被4
整除,否则元素不会相加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.