Question: #include #include #include using namespace std; using std::chrono::system_clock; void print_thread_info(int thread_num) { // Timer for calculating 5 seconds int timer = 0; while (true) {

#include #include #include

using namespace std;

using std::chrono::system_clock;

void print_thread_info(int thread_num)

{

// Timer for calculating 5 seconds

int timer = 0;

while (true)

{

timer++;

// Printing the message

cout << "Thread " << thread_num << " running." << endl;

if (timer == 5)

{

// Stopping the execution after 5 seconds

break;

}

// Sleeping the thread for 1 second, so that it prints the message every 1 second

this_thread::sleep_for(chrono::seconds(1));

}

}

int main()

{

int num_of_threads;

// Taking input from user

cout << "Enter the number of threads: ";

cin >> num_of_threads;

// Creating user passed number of threads

thread* threads = new thread[num_of_threads];

for (int i = 0; i < num_of_threads; i++)

{

// Calling the print_thread_info using each thread created

threads[i] = thread(print_thread_info, i);

// Joining the threads so that main will wait until all the threads get executed and then only stops it's execution

threads[i].join();

}

}

Using the code above to write a program that accepts an integer N as a command line input and then proceeds to launch N threads within that process on Windows system.

1.Each Thread should consist of an infinite loop that prints out Thread k running where k is a Thread index (from 0 to N-1).

2.After 5 seconds of running, your main program should kill Thread 0, then after another 5 seconds, should kill Thread 1, and so on until all Threades have been terminated. At that time, your main program should itself terminate.

Ex:

when the user input N=3

the CMD will display the following:

Thread : 0 Running

Thread : 1 Running

Thread : 2 Running

(after 1 second, the CDM will display the following again)

Thread : 0 Running

Thread : 1 Running

Thread : 2 Running

(after 1 second, the CDM will display the following again)

Thread : 0 Running

Thread : 1 Running

Thread : 2 Running

(after 1 second, the CDM will display the following again)

Thread : 0 Running

Thread : 1 Running

Thread : 2 Running

(after 1 second, the CDM will display the following again)

Thread : 0 Running

Thread : 1 Running

Thread : 2 Running

(after 1 second, start to Terminate Threads, Terminate Thread 0 first, the CDM will display the following)

Thread : 1 Running

Thread : 2 Running

(after 5 second , Terminate Thread 1, the CDM will display the following)

Thread : 2 Running

(after 5 second , Terminate Thread 2, the CDM will display the following)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!