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);
}
}
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);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.