In: Computer Science
How could we use Pthreads to find the minimum value in an array without mutex locks? Would this version be slower? If so, why?
What are PThreads?
The Pthread API: Pthreads API can be grouped into four->
Creating Threads:
Code for finding the minimum value in an array using pthreads:
# include <stdio.h>
# include <pthread.h>
# define N 10
struct StructMin{
int iMax;
int iMin;
};
int arr[N];
void *thread_search_min(void *para){
struct StructMin *st;
st=(struct StructMin*)malloc(sizeof(struct StructMin));
int i;
st->iMin=arr[N/2];
for(i=N/2 + 1;i<N;i++){
if(arr[i] < st->iMin){
st->iMin=arr[i];
}
}
pthread_exit((void*)st);
}
int main(){
pthread_t tid;
struct StructMin *st_main,*st_th;
int RetVal, i;
st_main=(struct StructMin*)malloc(sizeof(struct StructMin));
for(i=0;i<N;i++){
printf("Enter Value of arr[%d] :",i);
scanf("%d",&arr[i]);
}
pthread_create(&tid,NULL,thread_search_min,NULL);
st_main->iMin=arr[0];
for(i=1;i<N/2;i++){
if(arr[i] < st_main->iMin){
st_main->iMin=arr[i];
}
}
pthread_join(tid,(void**)&st_th);
if(st_main->iMin <=st_th->iMin){
RetVal=st_main->iMin;
}
else{
RetVal=st_th->iMin;
}
printf("Final Min : %d \n",RetVal);
return 0;
}
Algorithm:
Mutex Lock: A mutex lock is a mechanism that can be acquired by only one thread at a time. For other threads to get the same mutex, they must wait until it is released by the current owner of the mutex.
Would this version be slower and why?
I can say that It basically depends on the user or programmer ->
If you are using one lock per thread, so that's why when you use all the mutexes you don't see an increase in the execution time.
If all the threads are working on the same file, all they should be accessing it using the same lock (otherwise you will have incorrect results: all the threads trying to modify the file at the same time).
If you use just one global lock, and this is the worst-case scenario that many threads always trying to lock the same mutex may result in performance worse than a single thread serving all requests.
The most vital point is the waiting time. Your threads should spend only a fraction of their time waiting on mutexes. If they are waiting too often, then you are losing concurrency. The overhead costs of a mutex relate to the test-and-set operation and the system call that implements a mutex
Conclusion: A program without using mutex locks would be faster than using them. Besides, Implementing a program using mutex locks is much more secure if you have some functions which you shouldn't get access easily. And implementing using mutex locks in a proper way, like keeping them in same directory etcc. will increase execution time a very little bit and that can neglible if porperly implemented witout losing concurrency.