...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <mutex> #include <thread> const size_t max_threads = 10; void do_work(size_t i, std::mutex *lockppm) { std::lock_guard<std::mutex> guard(*lockppm); // Access data protected by the lock. } void start_threads(void) { std::thread threads[max_threads]; std::mutex lockm; for (size_t i = 0; i < max_threads; ++i) { threads[i] = std::thread(do_work, i, &lockm); } } |
Compliant Solution
This compliant solution eliminates the race condition by extending the lifetime of the lock:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <mutex> #include <thread> const size_t max_threads = 10; void do_work(size_t i, std::mutex *lockppm) { std::lock_guard<std::mutex> guard(*lockppm); // Access data protected by the lock. } std::mutex lockm; void start_threads(void) { std::thread threads[max_threads]; for (size_t i = 0; i < max_threads; ++i) { threads[i] = std::thread(do_work, i, &lockm); } } |
Compliant Solution
This compliant solution eliminates the race condition by joining the threads before the lockmutex's destructor is invoked:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <mutex> #include <thread> const size_t max_threads = 10; void do_work(size_t i, std::mutex *lockppm) { std::lock_guard<std::mutex> guard(*lockppm); // Access data protected by the lock. } void run_threads(void) { std::thread threads[max_threads]; std::mutex lockm; for (size_t i = 0; i < max_threads; ++i) { threads[i] = std::thread(do_work, i, &lockm); } for (size_t i = 0; i < max_threads; ++i) { threads[i].join(); } } |
...
Tool | Version | Checker | Description | |||
---|---|---|---|---|---|---|
| 5.0 | Can detect violations of this rule with CERT C Rule Pack | ||||
Parasoft C/C++test | 9.5 | BD-RES-FREE, BD-RES-INVFREE |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
Bibliography
[ISO/IEC 9899:201114882-2014] | 7.26.4.1, "The mtx_destroy Function[thread.mutex] "Mutual exclusion" |
...