In this task, you are required to write a simple C++ program using a struct to p
ID: 2247216 • Letter: I
Question
In this task, you are required to write a simple C++ program using a struct to pass multiple arguments to threads (namely, ID and data). Things to note: Your program should take the file name as a command line argument. For each thread created a message should be printed including the threads ID. Your program should create a thread for each line it reads from the file, and send that line to the thread to print as well as the threads ID. The thread should then print out the correct string. Remember this data has to be read and displayed in the order as seen in the file. You can create your own txt file for your testing. On demo days, you will be given a new txt for testing your code. Your output should look something like this.Explanation / Answer
The following program in c++ demonstrates how to pass structure data to thread. We start numbering threads from 1 and use that as Id. Please create a file input.txt with some text for the program to display.
#include <pthread.h>
#include <iostream>
#include <fstream>
using namespace std;
//structure to hold the data being passed to the thread
struct thread_data
{
int thread_id;
string line;
};
void *display_line( void *ptr );
int main()
{
pthread_t thread1;
string line;
ifstream infile("input.txt");
if(!infile.is_open())
{
cout << "Could not find file - input.txt" << endl;
return 1;
}
int tid = 1; //initialize thread id
while(infile >> line)
{
//create new thread data
thread_data data;
//fill in the data for the data
data.thread_id = tid ++;
data.line = line;
cout << "Creating thread: " << data.thread_id << endl;
//pass the pointer to fill up thread data
if(pthread_create( &thread1, NULL, display_line, (void*) &data))
{
cout << "Error creating thread. Exiting... " << endl;
return 1;
}
pthread_join( thread1, NULL); //wait for the thread to finish
}
infile.close();
return 0;
}
void *display_line( void *data )
{
//cast back to the thread_data type and print the data received in the thread
struct thread_data *d = (struct thread_data *)data;
cout << d->line << " [From Thread_ID: " << d->thread_id << "]"<< endl;
return NULL;
}
input file: input.txt
Hello
World
How
Are
You
output
Creating thread: 1
Hello [From Thread_ID: 1]
Creating thread: 2
World [From Thread_ID: 2]
Creating thread: 3
How [From Thread_ID: 3]
Creating thread: 4
Are [From Thread_ID: 4]
Creating thread: 5
You [From Thread_ID: 5]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.