In: Computer Science
(using C in a Linux environment and the POSIX pthreads library)
Write a program named Sort.c that accepts a list of numbers from the user. There are two threads: Main thread waits for the numbers to be entered by the user and for the second thread to finish sorting. It then asks user whether there are more lists or not. It will do this until the user indicates there are no more lists to be entered, at which point it will wait for the second thread to be finished sorting and then exits the program. Sorting and display thread waits for the user to be finished inputting the numbers from the list, and then will sort and print the numbers. It will do this each time the user enters the number (depending on if the main thread is told to continue accepting more numbers from the user).
*Edit* I'm not sure how much more clear it can be, as last "Expert" could not answer.
A C-program with two threads:
First thread asks user to enter 5 numbers and stores them in an array.
Second thread sorts the 5 numbers (the first thread at this point is "waiting" for the second thread to finish) and then prints the 5 numbers in order from least to greatest. Then it asks the user if they have more numbers to enter.
If yes, thread one is ran (asking the user for the 5 numbers), saves the 5 numbers in an array. Then the first thread again waits while the second thread sorts and prints the numbers in order. This loop continues until the user no longer wishes to enter a list of numbers.
#include <stdio.h>
#include <pthread.h>
void *sort(void *args) {
int *nums=(int*)args;
int i,j;
for(i=0;i<5;i++) {
int minIndex=i;
for(j=i+1;j<5;j++) {
if(nums[j]<nums[minIndex]) {
minIndex=j;
}
}
int temp=nums[i];
nums[i]=nums[minIndex];
nums[minIndex]=temp;
}
}
int main() {
int nums[5];
int choice=1;
int i;
do {
printf("Enter 5 numbers to sort: ");
for(i=0;i<5;i++) {
scanf("%d", &nums[i]);
}
pthread_t thread_id;
pthread_create(&thread_id, NULL, sort, nums);
pthread_join(thread_id, NULL);
printf("Sorted numbers are: ");
for(i=0;i<5;i++) {
printf("%d ", nums[i]);
}
printf("\n");
printf("Do you wish to enter more numbers? Enter 1 for yes, 0 for
no: ");
scanf("%d", &choice);
} while(choice==1);
return 0;
}