Introduction
Previously I've introduced the lambda expression in C++, I'll show a example how to use lambda expression in the multithreading. If you don't read it, here is link.
In the post, I will introduce three concept of multithreading and use an example to show how to do it in C++ Programming. The example is the random ten points generation.
- Create Thread
- Join
- Lock
Create Thread
To create a thread, we have two methods to achieve. One is the following code snippet.
auto task(float x, float y, float z) -> void {
...
}
auto worker = std::thread(task, x, y);
Other is the lambda expression.
auto worker = std::thread(
[](float x, float y, float z) { ... },
arg1,
arg2);
If you need to create a set of threads at the same time, you can utilize the std::vector
.
auto spawn(void) -> std::vector<std::thread> {
auto workers = std::vector<std::thread>();
workers.emplace_back(
[](float x, float y, float z) { ... },
x, y, z);
return workers;
}
auto workers = spawn();
Join
Once we create the threads, the thread-join is easy.
auto workers = spawn();
for (auto& worker : workers) {
worker.join();
}
Lock
We need to output the point(x, y, z) to the terminal.
workers.emplace_back(
[](float x, float y, float z) {
std::cout << "(" << x << ", " << y << ", " << z << ")";
},
x, y, z);
But, you will find the output is not the same for each time. To fix the issue, we can utilize std::mutex
.
std::mutex mtx;
workers.emplace_back(
[](float x, float y, float z) {
mtx.lock();
std::cout << "(" << x << ", " << y << ", " << z << ")";
mtx.unlock();
},
x, y, z);
Thank you for reading, see you next time.
Top comments (0)