DEV Community

Gapry
Gapry

Posted on • Edited on

4 1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay