O
O
Oleg2017-12-10 15:18:49
C++ / C#
Oleg, 2017-12-10 15:18:49

Threads (POSIX Threads) in C. How to terminate half of threads every iteration?

Hello, I have such a problem. You need to write a multi-threaded program to sort an array using the merge sort algorithm. The program receives two parameters as input, the size of the array (for sorting) and the number of threads. The array is filled with random numbers (for educational purposes). The size of the array and the number of threads will be a number to the power of 2. (That is, 2, 4, 8, 16, etc - also for simplicity for educational purposes). An example is an array with 16 elements and the number of threads is 4. When creating a thread, we pass the number "i" to the array, by which it will calculate the index in the array with which it will work, that is, for example, "thread 0" will sort from 0 to 4 (0.1, 2.3). And so are all the streams.
Here's my problem. After sorting, you need to "kill" the neighbor's stream and merge with its array. For example thread "0" kills thread "1" and call the merge function. (from position 0 to 8). And so on until there is one thread left that will merge the two pieces of the array. There is an array that stores the thread ID, the array size is always 64 (the maximum number of program threads).
As I understand it, you need to do everything through While until the number of threads is equal to 1. At each iteration, the threads will wait until everything is finished, after which there will be a "kill" :))))) But how to synchronize the threads so that after completion every second flow, and the one that did not end called the merge function?
PS Sorry, maybe I described everything very stupidly, but if suddenly someone understood and can help, then thank you very much))))

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question