Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::queue::empty() not thread-safe? Shouldn't const functions be thread-safe?

Why is the empty() function in std::queue not thread-safe? (See here.) Shouldn't const functions always be thread-safe, since it's read-only?

Maybe there may be some mutable variable in the class that may get written by the several threads?

like image 252
Frank Avatar asked Dec 04 '10 19:12

Frank


1 Answers

Methods that don't modify the data of a class are only thread-safe if the object is never modified by any method. Otherwise a method on another thread could change the object (under a lock, correctly) and calling queue::empty() on your thread without acquiring the lock could lead to a race condition (depending on its implementation).

like image 111
John Calsbeek Avatar answered Nov 15 '22 20:11

John Calsbeek