Question

C program: 1: Write a program that uses 5 threads. Initialize a shared variable with a...

C program:

1:

  • Write a program that uses 5 threads. Initialize a shared variable with a value of 100.
  • Each thread must add its Thread ID (tid) to the shared variable.
  • Once a thread has done the addition, print the ID of the thread. [Note: thread does the printing]
  • Output the value of the shared variable once all threads have finished incrementing it. [Note: main code does the printing]
  • Provide a text file with your comments on the results of activity 1 - show what was printed and make any comments relevant to your learnings on processes and multi-threading.

2:

  • Repeat the program but make a modification.
  • Add Mutex to provide control on modifying the variable. It is important to make use of mutexes so that only one thread is incrementing the shared variable at a time.
  • Add comments to your text file and provide results and observations for activity 2.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

1. C code for adding thread IDs without mutex -

#include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 #define SHRD_VALUE 100 static int sumValue; void *AddThreadIds(void *threadid) {    long tid = (long)threadid; //lineX    sumValue = sumValue + tid; //lineY    printf("Thread ID - %d\n", tid);    pthread_exit(NULL); } int main () {         pthread_t threads[NUM_THREADS];    int i;    for(i = 0; i < NUM_THREADS; i++ )       pthread_create(&threads[i], NULL, AddThreadIds, (void *)i);    for (int i = 0; i < NUM_THREADS; i++)         pthread_join(threads[i], NULL);        printf("Sum of all thread IDs - %d\n", sumValue+SHRD_VALUE);    pthread_exit(NULL); }

Output -

Thread ID - 0

Thread ID - 2

Thread ID - 3

Thread ID - 1

Thread ID - 4

Sum of all thread IDs - 110

Comments - The global variable sumValue is prone to get erroneous value at the end as multiple threads active at any point of time may change the value incorrectly. Mutex Ensures that such thinng never happens

2. C code for adding thread IDs with mutex -

#include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 #define SHRD_VALUE 100 static int sumValue; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *AddThreadIds(void *threadid) { pthread_mutex_lock(&m); long tid = (long)threadid; sumValue = sumValue + tid; printf("Thread ID - %d\n", tid); pthread_mutex_unlock(&m); pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; int i; for(i = 0; i < NUM_THREADS; i++ ) pthread_create(&threads[i], NULL, AddThreadIds, (void *)i); for (int i = 0; i < NUM_THREADS; i++) pthread_join(threads[i], NULL); printf("Sum of all thread IDs - %d\n", sumValue+SHRD_VALUE); pthread_exit(NULL); }

Output -

Thread ID - 2

Thread ID - 1

Thread ID - 0

Thread ID - 4

Thread ID - 3

Sum of all thread IDs - 110

I have added Mutex Lock & unlock codes at respective critical section place to ensure that only single thread is present in critical section at a given point of time.

Add a comment
Know the answer?
Add Answer to:
C program: 1: Write a program that uses 5 threads. Initialize a shared variable with a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The goal of this assignment is to write a multithreaded program (Task3.c) that explores synchronization challenge 1. Assume that we have a shared variable CurrentiD. This is initialized to 1 at t...

    The goal of this assignment is to write a multithreaded program (Task3.c) that explores synchronization challenge 1. Assume that we have a shared variable CurrentiD. This is initialized to 1 at the beginning. 2. Now create 5 threads in your program and assign ID 1,2,3,4,5 to them respectively. You can pass the ID as a parameter when you create the threads. Each of the threads will try to access the variable "CurrentiD" Whenever a thread acquires the variable, it checks...

  • How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses...

    How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses mutex to lock and unlock the shared resource (dotstr.sum) for access control as shown below. pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n", offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); 2. Modify dot1m.c program to use reader-writer lock (instead of mutex).      Replace the codes (for mutex) by the codes (for reader-writer lock).            To initialize reader-writer lock, pthread_rwlock_initializer.            At the end,...

  • Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the ...

    Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the merge sort algorithm. The basic steps of merge sort are: 1) divide a collection of items into two lists of equal size, 2) use merge sort to separately sort each of the two lists, and 3) combine the two sorted lists into one sorted list. Of course, if the collection of items is just asingle item then merge sort doesn’t need to perform the three steps,...

  • Write a cpp program Server.h #ifndef SERVER_H #define SERVER_H #include #include #include #include using namespace std;...

    Write a cpp program Server.h #ifndef SERVER_H #define SERVER_H #include #include #include #include using namespace std; class Server { public:    Server();    Server(string, int);    ~Server();    string getPiece(int); private:    string *ascii;    mutex access; }; #endif -------------------------------------------------------------------------------------------------------------------------- Server.cpp #include "Server.h" #include #include Server::Server(){} Server::Server(string filename, int threads) {    vector loaded;    ascii = new string[threads];    ifstream in;    string line;    in.open(filename);    if (!in.is_open())    {        cout << "Could not open file...

  • In this assignment, you will write a program in C++ which uses files and nested loops...

    In this assignment, you will write a program in C++ which uses files and nested loops to create a file from the quiz grades entered by the user, then reads the grades from the file and calculates each student’s average grade and the average quiz grade for the class. Each student takes 6 quizzes (unknown number of students). Use a nested loop to write each student’s quiz grades to a file. Then read the data from the file in order...

  • (C++ Program) 1. Write a program to allow user enter an array of structures, with each...

    (C++ Program) 1. Write a program to allow user enter an array of structures, with each structure containing the firstname, lastname and the written test score of a driver. - Your program should use a DYNAMIC array to make sure user has enough storage to enter the data. - Once all the data being entered, you need to design a function to sort the data in descending order based on the test score. - Another function should be designed to...

  • please write in C++ Write a program that uses a structure to store the following inventory...

    please write in C++ Write a program that uses a structure to store the following inventory data in a file: The data can be either read from a text file or the keyboard Item name (string) Quantity on hand(int) Wholesale cost(double) Retail Cost(double) The program should have a menu that allows the user to perform the following tasks: Add new records to the file Display any record in the file User will provide the name of the item or the...

  • Write a Java program to read customer details from an input text file corresponding to problem...

    Write a Java program to read customer details from an input text file corresponding to problem under PA07/Q1, Movie Ticketing System The input text file i.e. customers.txt has customer details in the following format: A sample data line is provided below. “John Doe”, 1234, “Movie 1”, 12.99, 1.99, 2.15, 13.99 Customer Name Member ID Movie Name Ticket Cost Total Discount Sales Tax Net Movie Ticket Cost Note: if a customer is non-member, then the corresponding memberID field is empty in...

  • In a sensible language ( any of C#/Java/Python) write a program which correctly calculates add, subtract,...

    In a sensible language ( any of C#/Java/Python) write a program which correctly calculates add, subtract, multiply and divide using our ‘minifloat’ binary format using an algorithm you code yourself.  Some details: Your program only needs to work on two ‘numbers’ at a time, read those in from a text file – failure to read those values from a text file will result in a grade of 0.   For each ‘number’ store the sign, exponent and mantissa separately.   You can hard code your...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT