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, use pthread_rwlock_destroy to remove the lock
Use pthread_rwlock_wrlock to lock the shared resource,
And use pthread_rwlock_unlok to unlock the shared resource
Here is dot1m.c
/**************************************************************** * FILE: dotprod_mutex.c * DESCRIPTION: * This example program illustrates the use of mutex variables * in a threads program. This version was obtained by modifying the * serial version of the program (dotprod_serial.c) which performs a * dot product. The main data is made available to all threads through * a globally accessible structure. Each thread works on a different * part of the data. The main thread waits for all the threads to complete * their computations, and then it prints the resulting sum. * SOURCE: Vijay Sonnad, IBM * LAST REVISED: 01/29/09 Blaise Barney ******************************************************************************/ #include <pthread.h> #include <stdio.h> #include <stdlib.h> /* The following structure contains the necessary information to allow the function "dotprod" to access its input data and place its output into the structure. This structure is unchanged from the sequential version. */ typedef struct { double *a; double *b; double sum; int veclen; } DOTDATA; /* Define globally accessible variables and a mutex */ /* now moved to main */ // #define NUMTHRDS 10 // #define VECLEN 100000 // pthread_t callThd[NUMTHRDS]; pthread_mutex_t mutexsum; DOTDATA dotstr; /* The function dotprod is activated when the thread is created. As before, all input to this routine is obtained from a structure of type DOTDATA and all output from this function is written into this structure. The benefit of this approach is apparent for the multi-threaded program: when a thread is created we pass a single argument to the activated function - typically this argument is a thread number. All the other information required by the function is accessed from the globally accessible structure. */ void *dotprod(void *arg) { /* Define and use local variables for convenience */ int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; /* Perform the dot product and assign result to the appropriate variable in the structure. */ mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } /* Lock a mutex prior to updating the value in the shared structure, and unlock it upon updating. */ 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); pthread_exit((void*) 0); } /* The main program creates threads which do all the work and then print out result upon completion. Before creating the threads, The input data is created. Since all threads update a shared structure, we need a mutex for mutual exclusion. The main thread needs to wait for all threads to complete, it waits for each one of the threads. We specify a thread attribute value that allow the main thread to join with the threads it creates. Note also that we free up handles when they are no longer needed. */ int main (int argc, char *argv[]) { // modify the program to get MUNTHRDS as the argument1 // and VECLEN as argument2 // that is, run the program: ./dotm 10 100000 // int NUMTHRDS = 10; int VECLEN = 100000; pthread_t callThd[NUMTHRDS]; long i; double *a, *b; void *status; pthread_attr_t attr; /* Assign storage and initialize values */ a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); for (i=0; i<VECLEN*NUMTHRDS; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = VECLEN; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, NULL); /* Create threads to perform the dotproduct */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<NUMTHRDS;i++) { /* Each thread works on a different set of data. * The offset is specified by 'i'. The size of * the data for each thread is indicated by VECLEN. */ pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); /* Wait on the other threads */ for(i=0;i<NUMTHRDS;i++) { pthread_join(callThd[i], &status); } /* After joining, print out the results and cleanup */ printf ("Sum = %f \n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(NULL); }
// readerWriterLock.cpp
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <map> #include <shared_mutex> #include <string> #include <thread> std::map<std::string,int> teleBook{{"Dijkstra",1972},{"Scott",1976},{"Ritchie",1983}}; std::shared_timed_mutex teleBookMutex; void addToTeleBook(const std::string& na, int tele){ std::lock_guard<std::shared_timed_mutex> writerLock(teleBookMutex); std::cout << "\nSTARTING UPDATE " << na; std::this_thread::sleep_for(std::chrono::milliseconds(500)); teleBook[na]= tele; std::cout << " ... ENDING UPDATE " << na << std::endl; } void printNumber(const std::string& na){ std::shared_lock<std::shared_timed_mutex> readerLock(teleBookMutex); std::cout << na << ": " << teleBook[na]; } int main(){ std::cout << std::endl; std::thread reader1([]{ printNumber("Scott"); }); std::thread reader2([]{ printNumber("Ritchie"); }); std::thread w1([]{ addToTeleBook("Scott",1968); }); std::thread reader3([]{ printNumber("Dijkstra"); }); std::thread reader4([]{ printNumber("Scott"); }); std::thread w2([]{ addToTeleBook("Bjarne",1965); }); std::thread reader5([]{ printNumber("Scott"); }); std::thread reader6([]{ printNumber("Ritchie"); }); std::thread reader7([]{ printNumber("Scott"); }); std::thread reader8([]{ printNumber("Bjarne"); }); reader1.join(); reader2.join(); reader3.join(); reader4.join(); reader5.join(); reader6.join(); reader7.join(); reader8.join(); w1.join(); w2.join(); std::cout << std::endl; std::cout << "\nThe new telephone book" << std::endl; for (auto teleIt: teleBook){ std::cout << teleIt.first << ": " << teleIt.second << std::endl; } std::cout << std::endl; }
typedef struct { double *a; double *b; double sum; int veclen; } DOTDATA;
void *dotprod(void *arg) { /* Define and use local variables for convenience */ int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; /* Perform the dot product and assign result to the appropriate variable in the structure. */ mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } /* Lock a mutex prior to updating the value in the shared structure, and unlock it upon updating. */ 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); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { // modify the program to get MUNTHRDS as the argument1 // and VECLEN as argument2 // that is, run the program: ./dotm 10 100000 // int NUMTHRDS = 10; int VECLEN = 100000; pthread_t callThd[NUMTHRDS]; long i; double *a, *b; void *status; pthread_attr_t attr; /* Assign storage and initialize values */ a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); for (i=0; i<VECLEN*NUMTHRDS; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = VECLEN; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, NULL); /* Create threads to perform the dotproduct */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<NUMTHRDS;i++) { /* Each thread works on a different set of data. * The offset is specified by 'i'. The size of * the data for each thread is indicated by VECLEN. */ pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); /* Wait on the other threads */ for(i=0;i<NUMTHRDS;i++) { pthread_join(callThd[i], &status); } /* After joining, print out the results and cleanup */ printf ("Sum = %f \n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(NULL); }
How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses...
In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...
Compile and run the deadlockFree.c program below and report if this program does go into deadlock or not. Modify this deadlockFree.c program so that you change the lock/unlock order of the mutexes. Experiment with the order of locks (and maybe extend the number of loop iterations) until you find a scenario where you can demonstrate deadlock. //Program: deadlockFree.c A simple threaded program to demonstrate the deadlock condition.Two threads are used to wait on two MUTEXES. Careful ordering of locks should...
I need help with the following question: P5: The program below has a parent thread that is a writer and 2 child threads that are both readers. Complete the "child" function so that readers can continuously print the value of x" whenever the writer is not writing. No reader should starve while the other reader is reading sem t mutex, Xw mutex; int x; int read count = 0; int main (int argc, char "argv[]) { sem init (&mutex, 0,...
Read given code RaceOrNot1.c and write all possible outputs of the program. Assume there will be no thread creation or joining failures or mutex failures. If you believe there is only one possible output, you just need to write that output. #include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t count_mutex3 = PTHREAD_MUTEX_INITIALIZER; int c[2] = {1,0}; void *UpdateC1(void *arg) { int i; for(i=0;i<1000000;i++) { pthread_mutex_lock(&count_mutex); c[0]=(c[0]+1)%2; c[1]=(c[1]+1)%2; pthread_mutex_unlock(&count_mutex); } return NULL; } void *UpdateC2(void *arg) { int...
In C using the following 2 files to create a 3rd file that uses multiple threads to improve performance. Split the array into pieces and each piece is handled by a different thread. Use 8 threads. run and compile in linux. #include <stdio.h> #include <sys/time.h> #define BUFFER_SIZE 4000000 int countPrime=0; int numbers[BUFFER_SIZE]; int isPrime(int n) { int i; for(i=2;i<n;i++) if (n%i==0) return 0; return 1; } int main() { int i; // fill the buffer for(i=0;i<BUFFER_SIZE;i++) numbers[i] = (i+100)%100000; //...
so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n) using semaphores implement solution to the critical section problem #include #include int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* threads call this function */ int main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of thread attributes */ if (argc != 2) { fprintf(stderr,"usage: a.out \n"); return -1; } if...
I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any help would be appreciated. /**** main.c ****/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <string.h> #define WORD_LEN 6 #define TOP 10 char * delim = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r"; struct Word { char word[30]; int freq; }; int threadCount; int fileDescriptor; int fileSize; off_t chunk; struct Word* wordArray; int arrIndex = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;...
Pleas help I need to create and array to add to my code something like this for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; ::::::::: CODE ::::::::::::: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> int sharedVar = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* thread handler */ void *threadHandler(void *vargp) { int i = 0; pthread_mutex_lock(&mutex); ...
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...
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...