Make a program intended to fail due to lack of protection of a global resource (
ID: 3542766 • Letter: M
Question
Make a program intended to fail due to lack of protection of a global resource (variable). Then you will implement the program with a protection mechanism and show that the protection is working
Create a global unprotected resource. Think simple; for example a variable that more than onethread read-modify-write should suffce.
The main() function of your program should create a congurable number of threads (e.g. use command line arguments to congure the number of threads). Each thread should access the global resource a given number of times (could also be congurable through a command line argument). When all of the threads have finished, the number of protection violations should
be printed on the console.
Below we outline the pseudo code for the main program. You may use either the pthread or
sthread library for your implementation in C.
1. Create a global resource G
2. Create N threads
3. Start the N threads
4. Wait for all N threads to complete their execution
5. Compare the expected result of G with the actual value, and print out OK/FAIL
Explanation / Answer
Compile using this command you have link pthreads library
program :
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUM_THREADS 4
int G=2;//Global resource
void *BusyWork(void *t)
{
int i;
long tid;
double result=0.0;
tid = (long)t;
printf("Thread %ld starting... ",tid);
if(tid%2==0){
for (i=0; i<10; i++)
{
result = result +G;
G+=1;
}}
else for (i=0; i<3; i++)
{
G*=2;
}
printf("Thread %ld done. Result = %e ",tid, result);
pthread_exit((void*) t);
}
int main (int argc, char *argv[])
{
pthread_t *thread;
pthread_attr_t attr;
int rc;
long t;
void *status;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int num_threads=atoi(argv[1]);
thread=(pthread_t *)calloc(num_threads, sizeof(pthread_t));
for(t=0; t<num_threads; t++) {
printf("Main: creating thread %ld ", t);
rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d ", rc);
exit(-1);
}
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&attr);
for(t=0; t<num_threads; t++) {
rc = pthread_join(thread[t], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d ", rc);
exit(-1);
}
printf("Main: completed join with thread %ld having a status f %ld ",t,(long)status);
}
if(G%2==0){printf("Main: program completed. OK ");}
else printf("Main: program completed. FAIL. ");
pthread_exit(NULL);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.