简体   繁体   English

有人可以向我解释这段代码的逻辑吗?

[英]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) (不包括)求和。

  • The 1st time sum_array is called, thread_part is 0 , and sum_array will sum elements [0,25) into sum[0] .第一次调用sum_arraythread_part0sum_array将元素 [0,25) 加到sum[0]中。
  • The 2nd time sum_array is called, thread_part is 1 , and sum_array will sum elements [25,50) into sum[1] .第二次调用sum_arraythread_part1sum_array将元素 [25,50) 加到sum[1]中。
  • The 3rd time sum_array is called, thread_part is 2 , and sum_array will sum elements [50,75) into sum[2] .第三次调用 sum_array , thread_part2sum_array sum_array加到sum[2]中。
  • The 4th time sum_array is called, thread_part is 3 , and sum_array will sum elements [75,100) into sum[3] .第 4 次调用 sum_array, thread_part3sum_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM