Operating system Using C++ 3. Write a multithreaded sorting program that works a
ID: 3934788 • Letter: O
Question
Operating system
Using C++
3. Write a multithreaded sorting program that works as follows: A list of integers is divided into two smaller lists of equal size. Two separate threads (sorting threads) sort each sub list using a sorting algorithm of your choice. The two sub lists are then merged by a third thread (a merging thread).
Explanation / Answer
#include #include #include #include #include struct Params { int *start; size_t len; int depth; }; // only used for synchronizing stdout from overlap. pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; // forward declare our thread proc void *merge_sort_thread(void *pv); // a simple merge algorithm. there are *several* more efficient ways // of doing this, but the purpose of this exercise is to establish // merge-threading, so we stick with simple for now. void merge(int *start, int *mid, int *end) { int *res = malloc((end - start)*sizeof(*res)); int *lhs = start, *rhs = mid, *dst = res; while (lhs != mid && rhs != end) *dst++ = (*lhs len, params->depth); return pv; } // public-facing api void merge_sort(int *start, size_t len) { merge_sort_mt(start, len, 4); // 4 is a nice number, will use 7 threads. } int main() { static const unsigned int N = 2048; int *data = malloc(N * sizeof(*data)); unsigned int i; srand((unsigned)time(0)); for (i=0; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.