简体   繁体   中英

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. I know how to create threads but cannot understand the sum 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.

  • The 1st time sum_array is called, thread_part is 0 , and sum_array will sum elements [0,25) into sum[0] .
  • The 2nd time sum_array is called, thread_part is 1 , and sum_array will sum elements [25,50) into sum[1] .
  • The 3rd time sum_array is called, thread_part is 2 , and sum_array will sum elements [50,75) into sum[2] .
  • The 4th time sum_array is called, thread_part is 3 , and sum_array will sum elements [75,100) into sum[3] .

The above is true as long as the calls to sum_array are sequential. However, I presume that sum_array is being called once by each of four simultaneously-running threads. 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.

To achieve the desired result, you need to make part++ atomic (eg using a lock). Better yet, pass thread_part as an argument to the thread.

Note that MAX must be evenly divisible by 4 or elements won't be summed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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