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

can any plz tell me how to code to synchronize 4 threads so theyprint out \"0\",

ID: 3614929 • Letter: C

Question

can any plz tell me how to code to synchronize 4 threads so theyprint out "0","1","2","3".

but with these rules

1.) the total number of "0's" and "1's" that has been printedat any point in the out string cant exceed the total number of 2'sand 3's that have been printed.

2.)after a 2 is printed, another 2 cannot be printed until one ormore 3's have been printed

3.) the total number of 0's that have been printed at any point inthe output cannot exceed twice the number of 1's that have beenprinted at the point

Explanation / Answer

#include<pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define NUM_THREADS 4
#define TCOUNT 4


int     count = 0;
int     thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex[4];

void * inc_count(void*t)
{
int i;
long my_id = (long)t;
while(1)
{
   pthread_mutex_lock(&count_mutex[(my_id)%4]);
    printf(""%d"",my_id);
   pthread_mutex_unlock(&count_mutex[(my_id+1)%4]);

    /*
    Check the value of count and signal waitingthread when condition is
    reached. Note that this occurs while mutexis locked.
    */
    /* Do some "work" so threads can alternate onmutex lock */
    sleep(1);
   }
pthread_exit(NULL);
}

int main (int argc, char*argv[])
{
int i, rc;
long t0=0,t1=1, t2=2, t3=3;
pthread_t threads[4];
pthread_attr_t attr;

/* Initialize mutexand condition variable objects */

for (i=0;i<TCOUNT; i++) {
pthread_mutex_init(&count_mutex[i], NULL);
    pthread_mutex_lock(&count_mutex[i]);
}
/* For portability, explicitly create threads in a joinablestate */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, inc_count, (void*)t0);
pthread_create(&threads[1], &attr, inc_count, (void*)t1);
pthread_create(&threads[2], &attr, inc_count, (void*)t2);
pthread_create(&threads[3], &attr, inc_count, (void*)t3);

   pthread_mutex_unlock(&count_mutex[0]);
/* Wait for all threads to complete */
for (i=0; i<NUM_THREADS; i++) {
    pthread_join(threads[i], NULL);
}
printf ("Main(): Waited on %d threads. Done. ",NUM_THREADS);

/* Clean up andexit */
pthread_attr_destroy(&attr);
pthread_exit(NULL);

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote