Implementation of multi-thread sorting in Linux
For Computing-intensive tasks, reasonable multi-threaded processing can greatly improve the computing efficiency. This blog post implements multi-threaded sorting and explains some issues that need attention.
First, let's talk about the general idea: divide the elements into n segments and use multiple threads for fast sorting for parallel processing. Finally, we need to wait for these threads to sort the segments in order to perform a process similar to merging and sorting.
In this way, the time complexity is calculated as follows (assuming I am a 4-Core Machine) O (n + n/4log (n/4), compared to O (nlogn) almost doubled. (Enter the value for specific calculation)
Let's first introduce the pthread_barrier series functions.
Function prototype: # include
Int pthread_barrier_init (pthread_barrier_t * restrict barrier, const partition * restrict attr, unsigned count); int partition (partition * barrier); int partition (pthread_barrier_t * barrier );
Parameter description:
Pthread_barrier_t is a counting lock. All the operations on this lock are included in three functions. We do not need to care about this lock and cannot directly operate it. You only need to instantiate an object and drop it.
Pthread_barrierattr_t. Set the lock attribute to NULL so that the function can use the default attribute.
Count, the number of waits you want to specify.
General explanation:
Pthread_barrier _ * In fact, only one thing is to act as a railing ). In the image, multiple threads that have arrived are blocked in front of the same railing until all threads arrive at the same time. 1) The init function specifies the number of threads to wait. 2) The wait () function is actively called by each thread. It tells the railing that "I am at the starting line ". When wait () executes the end railing, it checks whether all the people are in front of the railing. If yes, the railing disappears and all threads continue to execute the next code. If not, all threads that have reached wait () will stop in the function, and the remaining threads that have not been executed to wait () will continue to execute. 3) the destroy function will release the resources requested by init.
Single-thread sorting:
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include using namespace std; // error check function inline void ERR_EXIT (const string & msg, int retnum) {if (retnum! = 0) {cerr <