Question

In: Computer Science

Answer the following questions based on the given c file: #include #include #include    int c...

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):

  1. You should have observed output lines that were NOT always printed in integer order. This is because the code as written has a critical section that is being simultaneously run by more than one thread. What lines of the sample code constitute the critical section? You can cut and paste those lines into your answer, or you can type them in.  

  1. Thread safety (https://en.wikipedia.org/wiki/Thread_safety) is a concept often used when discussing subroutines or other code segments that are written in such way that they can be “multiply run” as parts of multiple threads that are being scheduled concurrently or otherwise multiprogrammed. Do you think that the function printf() is thread safe? Do some research and/or run some code experiments and provide a brief, but complete, answer that explains your view on the subject. Be sure to explain why you hold your position on the subject, no matter what that is.

Solutions

Expert Solution

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:


Related Solutions

*Answer in C program* #include <stdio.h> int main() {      FILE *fp1;      char c;     ...
*Answer in C program* #include <stdio.h> int main() {      FILE *fp1;      char c;      fp1= fopen ("C:\\myfiles\\newfile.txt", "r");      while(1)      {         c = fgetc(fp1);         if(c==EOF)             break;         else             printf("%c", c);      }      fclose(fp1);      return 0; } In the program above which statement is functioning for opening a file Write the syntax for opening a file What mode that being used in the program. Give the example from the program Referring to...
#include #include #include int main(void) { int feof(FILE *stdin); int i, num; int binary[10]; char input[10];...
#include #include #include int main(void) { int feof(FILE *stdin); int i, num; int binary[10]; char input[10]; printf("Starting the CPSC 1011 Decimal to Binary Converter!\n"); while(1) {    i=0;    printf("\nPlease enter a positive whole number (or EOF to quit): ");    scanf("%s", input); // user inputs value as a string for separate values    if(strcmp(input,"")==0) {        printf("\n\tThank you for using the CPSC 1011 Decimal to Binary Generator.\nGoodbye!\n\n");    return(0); } num=atoi(input); if (num<=0) {    printf("\n\tSorry, that was...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) {     FILE *myFile;...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) {     FILE *myFile;     char fname[20];     //int sum = 0;     int i, j, k, tmp =0;     int num = 0;     int mass = 0;     int count = 0;     int fuel = 0;     int total = 0;     int M[1000];     char ch;     char buffer[32];     printf(" Input the filename to be opened : ");     scanf("%s",fname);     myFile = fopen(fname, "r");     if(myFile == NULL)     {         printf("Can't open file\n");     } while(1)     {         ch =...
#include <stdio.h> int main() {      FILE *fp1;      char c;      fp1= fopen ("C:\\myfiles\\newfile.txt", "r");...
#include <stdio.h> int main() {      FILE *fp1;      char c;      fp1= fopen ("C:\\myfiles\\newfile.txt", "r");      while(1)      {         c = fgetc(fp1);         if(c==EOF)             break;         else             printf("%c", c);      }      fclose(fp1);      return 0; } In the program above which statement is functioning for opening a file Write the syntax for opening a file What mode that being used in the program. Give the example from the program Referring to the program above what...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to store user input bool cont = true; //implement a loop so that it will continue asking until the user provides a positive integer // the following provides ONLY part of the loop body, which you should complete { cout <<"How many words are in your message? \n"; cout <<"Enter value: "; // get user input integer here    cout <<"\nInvalid value. Please Re-enter a...
Research "Const Correctness" and answer the following questions: Given: class SimpleClass { private: int _x; public:...
Research "Const Correctness" and answer the following questions: Given: class SimpleClass { private: int _x; public: SimpleClass(int x) : _x(x){} int getX() const { return _x; } void setX(int newX) { _x = newX; } void displayDataWithCustomMessage(const string &customMessage) { cout<<"Data: "<<_x<<endl; cout<<"Custom Message: "<<customMessage<<endl; } }; What is the usefulness of the "const" keyword in the definition of the "getX" member function? What is the usefulness of the "const" keyword in the definition of the "displayDataWithCustomMessage" member function? Why...
What is the output of the following C program? #include<stdio.h> int fac (int x); void main(...
What is the output of the following C program? #include<stdio.h> int fac (int x); void main( ) {                         for (int i=1; i<=2; i++)                                     printf("%d", fac(i)); } int fac(int x) {                         x = (x>1) ? x + fac(x-1) : 100);                         return x; }
Please debug the code and answer the questions: #include <stdio.h> typedef struct node { int value;...
Please debug the code and answer the questions: #include <stdio.h> typedef struct node { int value; struct node *next; } node; int ll_has_cycle(node *first) { node * head = first; while (head->next) { head = head->next; if (head == first) return 1; } return 0; } void test_ll_has_cycle(void) { int i,j; node nodes[5]; for(i=0; i < sizeof(nodes)/sizeof(node); i++) { nodes[i].next = NULL; nodes[i].value = i; } nodes[0].next = &nodes[1]; nodes[1].next = &nodes[2]; nodes[2].next = &nodes[1]; printf("Checking first list for cycles....
given a input file, parse it and answer the following frequency related questions, using java. -list...
given a input file, parse it and answer the following frequency related questions, using java. -list the most frequent word(s) in the whole file and its frequency. -list sentence(s) with the max. number of occurrences of the word “of” in the entire file and also list the corresponding frequency. program has two arguments; 1st : path to the input text file 2nd : name prefix for the output files ex. $ java assgn1 “./input.txt” “output” outputs: for each question create...
Write a C++ program based on the cpp file below ++++++++++++++++++++++++++++++++++++ #include using namespace std; //...
Write a C++ program based on the cpp file below ++++++++++++++++++++++++++++++++++++ #include using namespace std; // PLEASE PUT YOUR FUNCTIONS BELOW THIS LINE // END OF FUNCTIONS void printArray(int array[], int count) {    cout << endl << "--------------------" << endl;    for(int i=1; i<=count; i++)    {        if(i % 3 == 0)        cout << " " << array[i-1] << endl;        else        cout << " " << array[i-1];    }    cout...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT