This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<thread> | |
#include<iostream> | |
using namespace std; | |
void print() | |
{ | |
//printing frm thread | |
for (int i = 10; i < 20; i++) | |
{ | |
cout <<"thread"<< i << endl; | |
} | |
} | |
void main() | |
{ | |
thread t(print);//creating a thread instance | |
for (int i = 1; i <10; i++) | |
{ | |
cout << "Main" << i << endl; | |
} | |
if (t.joinable()) //check if the thread is joinable | |
t.join();//main thread waits till child thread completes the task | |
cout << "main thread exiting" << endl; | |
} |
threadMain101
threadMain112
threadMain123
threadMain134
threadMain145
threadMain156
threadMain167
threadMain178
threadMain189
thread19
The output looks haphazard and not understandable. This is because both the main thread and the thread t are fighting for the common resource cout. We have to make a change in our code to control the access of cout. meaning if one thread is accessing cout, other thread has to simply wait for access.
We use std::mutex lock and unlock methods to do that.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void customcout(std::string&str, int i) | |
{ | |
mut.lock();//locks access | |
cout << str << i << endl; | |
mut.unlock();//releases access | |
} | |
void print() | |
{ | |
//printing frm thread | |
for (int i = 10; i < 20; i++) | |
{ | |
customcout(string("thread:"), i); | |
} | |
} | |
void main() | |
{ | |
thread t(print);//creating a thread instance | |
for (int i = 1; i <10; i++) | |
{ | |
customcout(string("Main:"), i); | |
} | |
if (t.joinable()) //check if the thread is joinable | |
t.join();//main thread waits till child thread completes the task | |
cout << "main thread exiting" << endl; | |
} |
thread:10
thread:11
thread:12
thread:13
thread:14
thread:15
thread:16
thread:17
thread:18
thread:19
Main:1
Main:2
Main:3
Main:4
Main:5
Main:6
Main:7
Main:8
Main:9
thread:11
thread:12
thread:13
thread:14
thread:15
thread:16
thread:17
thread:18
thread:19
Main:1
Main:2
Main:3
Main:4
Main:5
Main:6
Main:7
Main:8
Main:9
No comments:
Post a Comment