Now, let's see the usefulness of Lambda expressions for multithreading. In the following code, we are going to create five threads and put those into a vector container. Each thread will be using a Lambda function as the initialization function. The threads initialized in the following code are capturing the loop index by value:
int main() { std::vector<std::thread> threads; for (int i = 0; i < 5; ++i) { threads.push_back(std::thread( [i]() { std::cout << "Thread #" << i << std::endl; })); } std::cout << "nMain function"; std::for_each(threads.begin(), threads.end(), [](std::thread &t) { t.join(); }); }
The vector container threads store five threads that have been created inside the loop. They are joined at the end of...