Program output:
Read given code:RaceOrNot1.c and RaceOrNot2.c .Write all possible outputsof RaceOrNot1.c when it is run as “a.exe2” and all possible outputsof RaceOrNot2.c when it is run as "a.exe 3".Assume there will be no memory allocation errors, no threadcreation or joining failures, and no mutex or semaphore failures.If you believe there is only one possible output, you just need towrite that output. Pay attention to the note above.
RaceOrNot1.c Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
int gc[2] = {0,0};
void *UpdateC(void *arg) {
int i,index=(int)arg;
for(i=0;i<10000000;i++) {
gc[index%2]=(gc[index%2]+1)%2;
}
return NULL;
}
int main(int argc, char *argv[]) {
int rt,i,numThreads=atoi(argv[1]);
pthread_t*t=malloc(numThreads*sizeof(pthread_t));
assert(t!=NULL);
for(i=0;i<numThreads;i++) {
rt=pthread_create(&t, NULL,UpdateC, (void*)i);
if(rt!=0)
fprintf(stderr,"Thread%d creation failed: %d\n", i,rt);
}
for(i=0;i<numThreads;i++) {
rt=pthread_join(t, NULL);
if(rt!=0)
fprintf(stderr,"Waitfor thread %d failed: %d\n", i,rt);
}
printf("%d\t%d\n",gc[0],gc[1]);
return 0;
}//main
RaceOrNot2.c Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
int gc[2] = {0,0};
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
void *UpdateC(void *arg) {
int i,index=(int)arg;
for(i=0;i<10000000;i++) {
pthread_mutex_lock(&count_mutex);
int j=index%2;
pthread_mutex_unlock(&count_mutex);
gc[j]=(gc[j]+1)%2;
}
return NULL;
}
int main(int argc, char *argv[]) {
int rt,i,numThreads=atoi(argv[1]);
pthread_t*t=malloc(numThreads*sizeof(pthread_t));
assert(t!=NULL);
for(i=0;i<numThreads;i++) {
rt=pthread_create(&t, NULL,UpdateC, (void*)i);
if(rt!=0)
fprintf(stderr,"Thread%d creation failed: %d\n", i,rt);
}
for(i=0;i<numThreads;i++) {
rt=pthread_join(t, NULL);
if(rt!=0)
fprintf(stderr,"Waitfor thread %d failed: %d\n", i,rt);
}
printf("%d\t%d\n",gc[0],gc[1]);
return 0;
}//main
Program output: Read given code: RaceOrNot1.c and RaceOrNot2.c . Write all possible outputs of RaceOrNot1.c when it is
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Program output: Read given code: RaceOrNot1.c and RaceOrNot2.c . Write all possible outputs of RaceOrNot1.c when it is
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!