Created
December 7, 2018 05:54
-
-
Save Shylock-Hg/79f51e082585d01f14c1fd81ead64c8e to your computer and use it in GitHub Desktop.
Simple demo of c++ thread.
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 <iostream> | |
#include <thread> | |
// CPP program to demonstrate multithreading | |
// using three different callables. | |
#include <iostream> | |
#include <thread> | |
using namespace std; | |
// A dummy function | |
void foo(int Z) | |
{ | |
for (int i = 0; i < Z; i++) { | |
/* | |
clog << "Thread using function" | |
" pointer as callable\n"; | |
*/ | |
clog << "Thread " << "using " << "function " << "pointer " << "as " << "callable" << std::endl; | |
} | |
} | |
// A callable object | |
class thread_obj { | |
public: | |
void operator()(int x) | |
{ | |
for (int i = 0; i < x; i++) | |
/* | |
clog << "Thread using function" | |
" object as callable\n"; | |
*/ | |
clog << "Thread " << "using " << "function " << "object " << "as " << "callable" << std::endl; | |
} | |
}; | |
int main() | |
{ | |
clog << "Threads 1 and 2 and 3 " | |
"operating independently" << endl; | |
// This thread is launched by using | |
// function pointer as callable | |
thread th1(foo, 200); | |
// This thread is launched by using | |
// function object as callable | |
thread th2(thread_obj(), 200); | |
// Define a Lambda Expression | |
auto f = [](int x) { | |
for (int i = 0; i < x; i++) | |
/* | |
clog << "Thread using lambda" | |
" expression as callable\n"; | |
*/ | |
clog << "Thread " << "using " << "lambda " << "expression " << "as " << "callable" << std::endl; | |
}; | |
// This thread is launched by using | |
// lamda expression as callable | |
thread th3(f, 200); | |
// Wait for the threads to finish | |
// Wait for thread t1 to finish | |
th1.join(); | |
// Wait for thread t2 to finish | |
th2.join(); | |
// Wait for thread t3 to finish | |
th3.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment