Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C and Linux help Code for Lab 5 that is mentioned: #include <stdio.h> #include <

ID: 3829422 • Letter: C

Question

C and Linux help

Code for Lab 5 that is mentioned:

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
int shmid, status;
int *a, *b;
int i;

shmid = shmget(IPC_PRIVATE, sizeof(int), 0777|IPC_CREAT);
int *temp=(int *)shmat(shmid,0,0);
*temp=19530;

int start=1;
// for(i=0;i<5;i++)
// {
if (fork() == 0) {

b = (int *) shmat(shmid, 0, 0);
if(start==1)
{b[0]=19530;
start=0;
}
for( i=0; i< 5; i++) {
if(i==0)
b[0]=19530;
sleep(1);
b[0]-=5;
printf(" Child reads: %d ",b[0]);
}


shmdt(b);

}
else {

a = (int *) shmat(shmid, 0, 0);

  
for( i=0; i< 5; i++) {
sleep(1);
a[0] = a[0]/5;
printf("Parent writes: %d, ",a[0]);
}
wait(&status);

shmdt(a);

shmctl(shmid, IPC_RMID, 0);
}
}

Read the man page of the following functions pthread-create, pthread-join, pthread mutex-init, pthread mutex-lock, pthread-mu pthread.mutex-unlock, pthread-mutex-destroy. 3 par- tially completed programs have been provided for you to help teach you threads. For this lab you are to create an output similar to that of the previous lab (x-5, x/5, etc.). This time you are using threads though. Since threads share global variables, you may make x a global variable, thus you don't have to use a file or shared memory to modify it. There are two ways to do this lab, and you may choose either, but you must use multithreading: 1. You can create your threads inside the loop, and use pthread-join0 to control the flow. Thus 10 total threads will be created. 2. You can make each thread have its own loop, and use mutexes to control the flow. Thus 2 total threads are created. Following is a sample of the output that will be printed to the screen/terminal.

Explanation / Answer

The solution is based on pthread_join.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int x=19530;
int check=0;
// A normal C function that is executed as a thread when its name
// is specified in pthread_create()
void *myThreadFun1(void *vargp)
{
while(check)
{
sleep(1);
}
x=x-5;
printf("Thread 1: x=%d ",x);
check=1;
return NULL;
}
void *myThreadFun2(void *vargp)
{
while(!check)
{
sleep(1);
}
x=x/5;
printf("Thread 2: x=%d ",x);
check=0;
return NULL;
}

int main()
{
int i=0;
printf("x = %d ",x);
for(i=0;i<5;i++)
{
pthread_t tid1,tid2;
printf("ITERATION %d ",i+1);
pthread_create(&tid1, NULL, myThreadFun1, NULL);
pthread_create(&tid2, NULL, myThreadFun2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
}
exit(0);
}