Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Wordsmithing

...

Code Block
bgColor#ffcccc
langc
#include <mutex>
#include <thread>

const size_t max_threads = 10;

void do_work(size_t i, std::mutex *pm) {
  std::lock_guard<std::mutex> guard(*pm);

  // Access data protected by the lock.
}

void start_threads() {
  std::thread threads[max_threads];
  std::mutex m;

  for (size_t i = 0; i < max_threads; ++i) {
    threads[i] = std::thread(do_work, i, &m);
  }
}

...

This compliant solution eliminates the race condition by extending the lifetime of the lockmutex:

Code Block
bgColor#ccccff
langc
#include <mutex>
#include <thread>

const size_t max_threads = 10;

void do_work(size_t i, std::mutex *pm) {
  std::lock_guard<std::mutex> guard(*pm);

  // Access data protected by the lock.
}

std::mutex m;

void start_threads() {
  std::thread threads[max_threads];

  for (size_t i = 0; i < max_threads; ++i) {
    threads[i] = std::thread(do_work, i, &m);
  }
}

...