Question

For this week, please describe in your own words what multithreading is and how can multiple...

For this week, please describe in your own words what multithreading is and how can multiple threads run simultaneously on a single-processor system? Provide small code example and the result/output of running your code to demonstrate this behavior. Write a few sentences explaining your code and the result/output of running your code.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Multithreading:


Multithreading is running multiple functions or methods
at a time i.e multiple independent tasks are performed
parallely.These tasks run in threads.


C++ code is explained in commments:


#include <thread>
#include <iostream>

using namespace std;

void task1() { //create task 1 which will be run by thread 1
for(int i=0;i<5;++i){//lets do this to check task1 progress by task1
cout<<"Task1 :"<<i<<endl;
}
}

void task2() { //create task2 which will run by thread 2
for(int i=0;i<5;++i){//lets do this to check task1 progress by task2
cout<<"Task2 :"<<i<<endl;
}
}

int main (int argc, char ** argv) {
thread thread_1(task1);//run thread1 calls task1 function or method independently without blocking the next instruction
thread thread_2(task2);//now it will run thread2 calls task1 function or method independently

thread_2.join(); //you can wait here all threads to complete
thread_1.join();
return 0;
}

From below output task1 and task2 outputs parallely by thread 1 and thread2
//output:



Add a comment
Know the answer?
Add Answer to:
For this week, please describe in your own words what multithreading is and how can multiple...
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
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