
Concept explainers
This is some code in C for quicksort. The quicksort works correctly, but I am trying to implement multithreading. I am trying to run the recursive calls in parallel with a limit on how much threads can be running at one time (set by the global variable 'maximumThreads'). My logic is incorrect with managing how many threads can be ran at the same time. The part that I need you to look at is after the for loop in quick sort, where I have my logic for the mutex and the conditional variable. Right now when I run my code, the program runs without stopping. I would like help with correctly implementing this.
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#define SORT_THRESHOLD 40
typedef struct _sortParams {
char** array;
int left;
int right;
int* currentThreads;
pthread_mutex_t* mutex;
pthread_cond_t* cond_var
} SortParams;
static int maximumThreads; /* maximum # of threads to be used */
/* This is an implementation of insert sort, which although it is */
/* n-squared, is faster at sorting short lists than quick sort, */
/* due to its lack of recursive procedure call overhead. */
static void insertSort(char** array, int left, int right) {
int i, j;
for (i = left + 1; i <= right; i++) {
char* pivot = array[i];
j = i - 1;
while (j >= left && (strcmp(array[j],pivot) > 0)) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = pivot;
}
}
/* Recursive quick sort, but with a provision to use */
/* insert sort when the range gets small. */
static void quickSort(void* p) {
SortParams* params = (SortParams*) p;
char** array = params->array;
int left = params->left;
int right = params->right;
int i = left, j = right;
if (j - i > SORT_THRESHOLD) { /* if the sort range is substantial, use quick sort */
int m = (i + j) >> 1; /* pick pivot as median of */
char* temp, *pivot; /* first, last and middle elements */
if (strcmp(array[i],array[m]) > 0) {
temp = array[i]; array[i] = array[m]; array[m] = temp;
}
if (strcmp(array[m],array[j]) > 0) {
temp = array[m]; array[m] = array[j]; array[j] = temp;
if (strcmp(array[i],array[m]) > 0) {
temp = array[i]; array[i] = array[m]; array[m] = temp;
}
}
pivot = array[m];
for (;;) {
while (strcmp(array[i],pivot) < 0) i++; /* move i down to first element greater than or equal to pivot */
while (strcmp(array[j],pivot) > 0) j--; /* move j up to first element less than or equal to pivot */
if (i < j) {
char* temp = array[i]; /* if i and j have not passed each other */
array[i++] = array[j]; /* swap their respective elements and */
array[j--] = temp; /* advance both i and j */
} else if (i == j) {
i++; j--;
} else break; /* if i > j, this partitioning is done */
}
pthread_mutex_lock(params->mutex);
// Wait if the maximum number of threads is reached
while(*params->currentThreads >= maximumThreads) {
pthread_cond_wait(params->cond_var, params->mutex);
}
// Increment the current thread count
(*params->currentThreads)++;
pthread_mutex_unlock(params->mutex);
SortParams first = {params->array, left, j, params->currentThreads, params->mutex, params->cond_var};
SortParams second = {params->array, i, right, params->currentThreads, params->mutex, params->cond_var};
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, (void*)quickSort, &first);
pthread_create(&thread2, NULL, (void*)quickSort, &second);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// After the threads finish, decrement the current thread count
// and signal any waiting threads
pthread_mutex_lock(params->mutex);
(*params->currentThreads)--;
pthread_cond_signal(params->cond_var);
pthread_mutex_unlock(params->mutex);
} else insertSort(array,i,j); /* for a small range use insert sort */
}
/* user interface routine to set the number of threads sortT is permitted to use */
void setSortThreads(int count) {
maximumThreads = count;
}
/* user callable sort procedure, sorts array of count strings, beginning at address array */
void sortThreaded(char** array, unsigned int count) {
SortParams parameters;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;
int currentThreads = 0;
parameters.array = array; parameters.left = 0; parameters.right = count - 1;
parameters.currentThreads = ¤tThreads; parameters.mutex = &mutex;
parameters.cond_var = &cond_var;
quickSort(¶meters);
pthread_cond_destroy(&cond_var);
pthread_mutex_destroy(&mutex);
}

Trending nowThis is a popular solution!
Step by stepSolved in 4 steps

I don't see the logic in here that limits the number of threads. How can we do that?
I don't see the logic in here that limits the number of threads. How can we do that?
- the following questions can be done without a textbook, short answer questionsarrow_forwardHello, could you assist me with this code? I'm encountering difficulties and I'm unsure how to proceed. The code needs to be written in C. I've included my current code below for reference.question:You need to use the pthread for matrix multiplication. Each thread from the threadpool should be responsible for computing only a part of the multiplication (partial product as shown in the above picture –all Ti(S) are called a partical product). Your main thread should split the matrices accordingly and create the partial data arrays that are needed to compute each Ti. You must create a unique task with thedata and submit it to the job queue. You can compute the partial products concurrently as long as you have threads available in the threadpool. You have to remove the task the from queue and submitto a thread in the threadpool. You should define the number of threads to be 5 and keep it dynamic so that we can test the same code with a higher or lower number of threads as needed. When…arrow_forwarddo you think that the reason for the relative efficiency of hashtables (and dictionaries) overother forms of arrays, as explained in the book (Downey, Think Python, p, 104), is similar to the difference of recursive functions and loops?arrow_forward
- Is there a way to optimize the following multithreaded quick sort algorithm, in C? I am looking for suggestions to make it run faster. I am trying to get closer to the qsort function's time. I don't want anything too complicated, like thread pooling. Here is the code: #include <stdio.h>#include <stdlib.h>#include <errno.h>#include <string.h>#include <pthread.h>#include <time.h>#define SORT_THRESHOLD 40typedef struct _sortParams {char** array;int left;int right;int* threadsLeft; // A counter to keep track of how many more threads are available to be created.pthread_mutex_t* mutex;} SortParams;static int maximumThreads; /* maximum # of threads to be used */static void insertSort(char** array, int left, int right) {int i, j;for (i = left + 1; i <= right; i++) {char* pivot = array[i];j = i - 1;while (j >= left && (strcmp(array[j], pivot) > 0)) {array[j + 1] = array[j];j--;}array[j + 1] = pivot;}}/*** This function uses a mutex to…arrow_forwardcan you do this in Java, please? Thank youarrow_forwardTo solve the problem of mismatch between the speeds of computer and printer, we usually use a buffer. Computer writes data to the buffer, and then printers get data from buffer. Which data structure could be used to implement the buffer? (A) Stack (B) Queuearrow_forward
- Please can you help me with the code that I have contributed, as I played a role in its development. Please ensure that only my code is utilized. This code should be written in C, and I have provided a portion of it below. Question that I need help with: You need to use the pthread for matrix multiplication. Each thread from the threadpool should be responsible for computing only a partof the multiplication (partial product as shown in the above picture –all Ti(S) are called a partical product). Your main thread should splitthe matrices accordingly and create the partial data arrays that areneeded to compute each Ti. You must create a unique task with thedata and submit it to the job queue. You can compute the partialproducts concurrently as long as you have threads available in thethreadpool. You have to remove the task the from queue and submitto a thread in the threadpool. You should define the number ofthreads to be 5 and keep it dynamic so that we can test the samecode with a…arrow_forwardYou write "call puts wrt ..plt" and assemble, link, and run the code. a. What does the call point to? b. What does the PLT entry point to? c. What does the GOT entry point to? d. Who fills in the PLT entry? The assembler, the linker, or the loader? e. Who fills in the GOT entry? The assembler, the linker, or the loader?arrow_forwardI need help with this pratice run question. In C++, Implement a Hash Table of size 8191 (= 2^13 - 1) to store integers based on quadratic probing. Design your own hash function that is, in your view, sufficiently non-trivial and efficient to compute. Compare the average number of probes for the following cases:Generate 4000 integer random numbers in the range 0 to 10^6 - 1, and insert them into the hash table. Compute and print the total number of probes.Repeat step (a) above 10 times, and find the average number of probes over these 10 trialsarrow_forward
- Multi-tasking can not be achieved with a single processor machine. True False 2. Async/Await is best for network bound operations while multi-threading and parallel programming is best for CPU-bound operations. True False 3. The following is a characteristic of an async method:The name of an async method, by convention, ends with an "Async" suffix. True False 4. Using asynchronous code for network bound operations can speed up the time needed to contact the server and get the data back. True False 5. Asynchronous programming has been there for a long time but has tremendously been improved by the simplified approach of async programming in C# 5 through the introduction of: The Task class True Falsearrow_forwardExamine the stack's efficiency when left to its own devices.arrow_forwardThis question was rejected because lack of a text file, which I do not see a way to upload. I saved the first part of the file as an image because that is all I can upload. If that doesn't suffice, please advise how to include a text file. In C++, I would like some help improving or making a better password lookup function for a Hash Table class/program I made, The function: it is supposed to lookup a user password using their ID and name which I read in from a text file. The one I have only works for the first 10 records, which I highlighted below in the program. string lookupPassword (string inUserID, string inUserName){ string thePassword; ... return thePassword; } Here is part of the program thus far: // Hash.cpp #include <iostream>#include<string>#include<iomanip>#include<fstream>using namespace std;//node classclass nodeBST {private: //user data string userID; string userName; string userPW; //BST left and right children nodeBST*…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





