- Examples
Let’s take a look at examples for creating threads, thread lifetimes, and thread methods.
We'll cover the following...
Example 1
Press + to interact
#include <iostream> //threadCreate.cpp#include <thread>void helloFunction(){std::cout << "Hello C++11 from a function." << std::endl;}class HelloFunctionObject {public:void operator()() const {std::cout << "Hello C++11 from a function object." << std::endl;}};int main(){std::cout << std::endl;// thread executing helloFunctionstd::thread t1(helloFunction);// thread executing helloFunctionObjectHelloFunctionObject helloFunctionObject;std::thread t2(helloFunctionObject);// thread executing lambda functionstd::thread t3([]{std::cout << "Hello C++11 from lambda function." << std::endl;});// ensure that t1, t2 and t3 have finished before main thread terminatest1.join();t2.join();t3.join();std::cout << std::endl;};
Explanation
-
All three threads (
t1
,t2
, andt3
) write their messages to the console. The work package of threadt2
is a function object (lines 8 - 13). The work package of thread ...
Access this course and 1400+ top-rated courses and projects.