DEV Community

Gapry
Gapry

Posted on • Updated on

Multithreading in C++

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.

  1. Create Thread
  2. Join
  3. 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);
Enter fullscreen mode Exit fullscreen mode

Other is the lambda expression.

auto worker = std::thread(
  [](float x, float y, float z) { ... }, 
  arg1, 
  arg2);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Join

Once we create the threads, the thread-join is easy.

auto workers = spawn();
for (auto& worker : workers) {
  worker.join();  
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, see you next time.

References

  1. std::thread
  2. std::uniform_real_distribution
  3. Race Condition

Top comments (0)