Home >Backend Development >C++ >Does `const` in C 11 Guarantee Thread Safety?
It is widely believed that employing 'const' in C 11 guarantees thread safety. However, this notion requires further clarification.
While 'const' alone does not guarantee thread safety, it fulfills the Standard Library's expectation that operations on 'const' objects are thread-safe. Specifically:
Unlike Java's 'synchronized,' 'const' does not inherently provide synchronization. Consider the following example:
class rect { int width = 0, height = 0; public: void set_size(int new_width, int new_height) { width = new_width; height = new_height; } int area() const { return width * height; } };
To properly utilize 'const' for thread safety with writes, mutable state (like a cached area value) must be protected by synchronization primitives, as demonstrated below:
class rect { int width = 0, height = 0; mutable std::mutex cache_mutex; mutable int cached_area = 0; mutable bool cached_area_valid = true; public: void set_size(int new_width, int new_height) { if (new_width != width || new_height != height) { std::lock_guard< std::mutex > guard(cache_mutex); cached_area_valid = false; } width = new_width; height = new_height; } int area() const { std::lock_guard< std::mutex > guard(cache_mutex); if (!cached_area_valid) { cached_area = width * height; cached_area_valid = true; } return cached_area; } };
Despite 'area()' being thread-safe, 'rect' still remains non-thread-safe due to unprotected writes in 'set_size()'.
The claim that C developers are running out of keywords is true, as the language has had a limited number of reserved words since its inception.
The above is the detailed content of Does `const` in C 11 Guarantee Thread Safety?. For more information, please follow other related articles on the PHP Chinese website!