
Database System Concepts
7th Edition
ISBN: 9780078022159
Author: Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher: McGraw-Hill Education
expand_more
expand_more
format_list_bulleted
Concept explainers
Question
In C, using this interface:
void setSortThreads(int count);
void sortThreaded(char** array, unsigned int count);
void sortThreaded(char** array, unsigned int count);
How can you modify the following quicksort program in order to use multithreading, with the goal of performing faster than qsort for large data sets? Use basic parallelization and limit the number of threads to the amount held by the global variable maximumThreads, specified by the user (when they call setSortThreads in the main function). If possible it would be helpful to test the code on a big text file, like maybe the dictionary. I'll include a sample main function at the end that I have been using. You would need your own text file to test it on, though.
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define SORT_THRESHOLD 40
typedef struct _sortParams {
char** array;
int left;
int right;
} 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 */
}
SortParams first; first.array = array; first.left = left; first.right = j;
quickSort(&first); /* sort the left partition */
SortParams second; second.array = array; second.left = i; second.right = right;
quickSort(&second); /* sort the right partition */
} 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;
parameters.array = array; parameters.left = 0; parameters.right = count - 1;
quickSort(¶meters);
}
int compareStrings(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
// Open the file
FILE *file = fopen("lorem", "r");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
// Estimate the number of words or lines; you can adapt this based on your file
int estimatedCount = 1000;
char **array = malloc(estimatedCount * sizeof(char *));
char buffer[100]; // assuming each word or line won't exceed 100 characters
unsigned int count = 0;
while (fscanf(file, "%s", buffer) != EOF) { // reading word by word
array[count] = strdup(buffer);
count++;
if (count >= estimatedCount) {
estimatedCount *= 2;
array = realloc(array, estimatedCount * sizeof(char *));
}
}
fclose(file);
// Duplicate array for qsort
char *qsortArray[count];
for (int i = 0; i < count; ++i) {
qsortArray[i] = array[i];
}
// Set number of threads
setSortThreads(4);
// Time sortThreaded
clock_t start = clock();
sortThreaded(array, count);
clock_t end = clock();
double sortThreaded_time = ((double) (end - start)) / CLOCKS_PER_SEC;
// Time qsort
start = clock();
qsort(qsortArray, count, sizeof(char *), compareStrings);
end = clock();
double qsort_time = ((double) (end - start)) / CLOCKS_PER_SEC;
// Output timing results
printf("Time taken by sortThreaded: %e seconds\n", sortThreaded_time);
printf("Time taken by qsort: %e seconds\n", qsort_time);
// Validate that the array is sorted
for (int i = 0; i < count - 1; ++i) {
if (strcmp(array[i], array[i + 1]) > 0) {
printf("sortThreaded failed at index %d\n", i);
return 1;
}
}
printf("Array sorted successfully by sortThreaded!\n");
// Free allocated memory for strings
for (int i = 0; i < count; ++i) {
free(array[i]);
}
free(array);
return 0;
}
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
// Open the file
FILE *file = fopen("lorem", "r");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
// Estimate the number of words or lines; you can adapt this based on your file
int estimatedCount = 1000;
char **array = malloc(estimatedCount * sizeof(char *));
char buffer[100]; // assuming each word or line won't exceed 100 characters
unsigned int count = 0;
while (fscanf(file, "%s", buffer) != EOF) { // reading word by word
array[count] = strdup(buffer);
count++;
if (count >= estimatedCount) {
estimatedCount *= 2;
array = realloc(array, estimatedCount * sizeof(char *));
}
}
fclose(file);
// Duplicate array for qsort
char *qsortArray[count];
for (int i = 0; i < count; ++i) {
qsortArray[i] = array[i];
}
// Set number of threads
setSortThreads(4);
// Time sortThreaded
clock_t start = clock();
sortThreaded(array, count);
clock_t end = clock();
double sortThreaded_time = ((double) (end - start)) / CLOCKS_PER_SEC;
// Time qsort
start = clock();
qsort(qsortArray, count, sizeof(char *), compareStrings);
end = clock();
double qsort_time = ((double) (end - start)) / CLOCKS_PER_SEC;
// Output timing results
printf("Time taken by sortThreaded: %e seconds\n", sortThreaded_time);
printf("Time taken by qsort: %e seconds\n", qsort_time);
// Validate that the array is sorted
for (int i = 0; i < count - 1; ++i) {
if (strcmp(array[i], array[i + 1]) > 0) {
printf("sortThreaded failed at index %d\n", i);
return 1;
}
}
printf("Array sorted successfully by sortThreaded!\n");
// Free allocated memory for strings
for (int i = 0; i < count; ++i) {
free(array[i]);
}
free(array);
return 0;
}
Expert Solution

This question has been solved!
Explore an expertly crafted, step-by-step solution for a thorough understanding of key concepts.
Step by stepSolved in 6 steps with 6 images

Knowledge Booster
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.Similar questions
- Provide simple explanationarrow_forwardWrite the assembly code for the safe_input function in the C program given below. Name the file as safeinputfile.asm. #include <stdio.h> int safe_input(char *buffer, unsigned length ); int main(){ char buffer[32]; printf("Your name: "); fflush(stdout); safe_input(buffer,32); printf("Pleased to meet you, %s!\n",buffer); return 0;}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
- Can you fix the code of the completion time based on the last execution of each process in the gantt chart and the output of the completion time must be the same as the image below?Code: #include <iostream>#include <queue>#include <string>#include <vector> struct Process { int processId; int burstTime; int priority;}; void print_gantt_chart(const std::vector<std::pair<int, int>>& gantt_chart) { std::cout << "Gantt Chart:" << std::endl; std::cout << "----------------------------------------------------------------------------" << std::endl; std::cout << "| "; for (const auto& process : gantt_chart) { std::cout << "P" << process.first << " | "; } std::cout << std::endl; std::cout << "----------------------------------------------------------------------------" << std::endl; std::cout << "0 "; int currentTime = 0; for (const…arrow_forwardYour task for this assignment is to implement a stack data structure in C++. This may be accomplished by utilizing the C++ standard template library (STL) or by utilizing a user-defined class. 1. 2. 3. 4. Implement a stack data structure using C++. The program will be interactive. Data transactions will be entered as a batch of transactions in a text file at the command line using redirection. The result of each transaction will be displayed on the console. For example: $ prog3 < prog3.dat Each input transaction will contain an arithmetic expression in post-fix format. Assume that each operand and operation (+,-, *, /, %, ^) is a single character in each arithmetic expression without spacing. You may assume that each arithmetic expression is correctly formatted. However, your program should not attempt the following: a. Divide by zero with / or % ... Instead, your program should display an error message and then begin evaluating a new input transaction. b. Perform % with non-integer…arrow_forward
arrow_back_ios
arrow_forward_ios
Recommended textbooks for you
- 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

Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education

Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON

Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON

C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON

Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning

Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education