- Examples

Let’s take a look at examples for creating threads, thread lifetimes, and thread methods.

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 helloFunction
std::thread t1(helloFunction);
// thread executing helloFunctionObject
HelloFunctionObject helloFunctionObject;
std::thread t2(helloFunctionObject);
// thread executing lambda function
std::thread t3([]{std::cout << "Hello C++11 from lambda function." << std::endl;});
// ensure that t1, t2 and t3 have finished before main thread terminates
t1.join();
t2.join();
t3.join();
std::cout << std::endl;
};

Explanation

  • All three threads (t1, t2, and t3) write their messages to the console. The work package of thread t2 is a function object (lines 8 - 13). The work package of thread ...

Access this course and 1400+ top-rated courses and projects.