Complete the following program which creates 5 copies of a thread with different
ID: 3866214 • Letter: C
Question
Complete the following program which creates 5 copies of a thread with different parameters. Specifically, the thread gets a character (ch), an integer number (n), and a double value (d) as parameters. Then the thread simply outputs the given character, integer number, and double value on the screen. /* suppose all necessary libraries are included here *//* Declare structure that you may need */ void *mythread(void *args) {// void main(int argc, char *argv[]) {////Suppose the parameters that will be passed to 5 copies of //threads are stored in the local arrays declared below. //CH[0], N[0], D[0] will be passed to thread 0, and so on. char CH[5] = "ABCDE": int N[5] = {3, 5, 8, 12, 21): double D[5] = {2.5, 3.6, 4.7, 5.8, 6.9): pthread_t tid[5]: for(i = 0: iExplanation / Answer
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std ;
#define NUM_THREADS 5
struct thread_data{
int thread_id;
char ch[6] = "ABCDE";
int N[5] = {3,5,8,12,21};
double D[5] = {2.5, 3.6, 4.7, 5.8, 6.9};
};
void *PrintHello(void *threadarg) {
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
cout << "Thread ID : " << my_data->thread_id ;
cout << " data " << my_data->ch[my_data->thread_id] << " "<<my_data->N[my_data->thread_id] << " "<<my_data->D[my_data->thread_id];
}
main()
{
pthread_t thread1, thread2;
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
void *status;
int rc;
for( int i=0; i < NUM_THREADS; i++ ){
cout <<"creating thread, " << i << endl;
td[i].thread_id = i;
//td[i].message = "This is message";
rc = pthread_create(&threads[i], &attr, PrintHello, (void *)&td[i]);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_attr_destroy(&attr);
for( int i=0; i < NUM_THREADS; i++ ){
pthread_join(threads[i], &status);
}
pthread_exit(NULL);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.