In: Computer Science
Answer the following questions based on the given c file:
#include
#include
#include
int c = 0;
void *fnC()
{ int i;
for(i=0;i<10;i++)
{ c++;
printf(" %d", c);
}
}
int main()
{
int rt1, rt2; pthread_t t1, t2; int trial_count = 0;
// For every trial, lets zero out the counter and run the count routine “twice”
// as threads that can be scheduled onto independent cores instead of running
// in sequence.
for (trial_count = 0; trial_count < 1000; trial_count++)
{
c = 0;
// Create two thread with the routine pthread_create(). You can use
// reference materials to get definitions of what the various parameters
// mean.
if((rt1=pthread_create( &t1, NULL, &fnC, NULL)))
printf("Thread creation failed: %d\n", rt1);
if((rt2=pthread_create( &t2, NULL, &fnC, NULL)))
printf("Thread creation failed: %d\n", rt2);
// Wait for both threads to finish. The main process thread will block
// until the threads that were launched terminate. Once they both finish,
// then the “main thread” unblocks and continues.
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("\n");
}
return 0;
}
Activity A, Task 1: Discussion Questions (10/50 points):
Working code implemented in C and appropriate comments provided for better understanding.
Here I am attaching code for all files:
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int c = 0;
pthread_mutex_t lock;
void *fnC()
{
int i;
for(i=0;i<10;i++)
{ //pthread_mutex_lock(&lock);
c++;
printf(" %d", c);
//pthread_mutex_unlock(&lock);
}
}
int main()
{
int rt1, rt2;
pthread_t t1, t2;
int trial_count = 0;
pthread_mutex_init(&lock, NULL);
for (trial_count = 0; trial_count < 1000; trial_count++)
{
c = 0;
/* Create two threads */
if( (rt1=pthread_create( &t1, NULL, &fnC, NULL)) )
printf("Thread creation failed: %d\n", rt1);
if( (rt2=pthread_create( &t2, NULL, &fnC, NULL)) )
printf("Thread creation failed: %d\n", rt2);
/* Wait for both threads to finish */
pthread_join( t1, NULL);
pthread_join( t2, NULL);
printf ("\n");
}
return 0;
}
Sample Output Screenshots: