简体   繁体   中英

How to calculate the average of numbers in a text file using threads in C programming?

How to calculate the average of numbers in a text file line by line (ex: average of numbers in line 1 = xxx, average of numbers in line 2 = yyy ....) using threads in C programming

● Read line by line from the file.

● Once a record of the data set is taken by a thread, the same data set should not be taken by another thread.

● Calculate the average of each line and write to another file.

Assuming this is a multi-threading assignment in C, store all numbers in an array X. Then create two arrays A1 and A2, each of half the total number of lines in the file. In the array A1, store all the odd position numbers from X. Store all even position numbers from X. Now spawn two threads, each being passed one of the arrays A1 and A2 as arguments. Have each thread store the total sum of all the elements of their respective arrays in some separate variable. Now after both threads end execution, add both sums from the threads and divide it by the number of lines.

When using threads, it is important that you avoid race conditions. Here, it can happen if one of your threads tries to figure out which line to read from, and the other one tries to update that value. Hence, you should use a Mutex . Each thread that needs to read or write the mutex variable (line_number etc.) acquires a lock, so if other threads try to access that variable they will suspend until the mutex is unlocked. Besides that, it is just the matter of creating threads and making them read from the file. For some examples of how to create threads and use mutexes with them look at the links below:

https://www.thegeekstuff.com/2012/05/c-mutex-examples/?refcom

Mutex lock threads

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