Consider the following code snippet:
thread 1:
while (true) {
task = fetch_task();
{
lock_guard<mutex> lock(my_mutex);
// modify content of my_list
my_list.push_back(task);
}
}
thread 2:
while (true) {
if (!my_list.empty()) {
{
lock_guard<mutex> lock(my_mutex);
// modify content of my_list
if (!my_list.empty()) {
task = my_list.pop_front();
}
}
if (taks) {
handle_taks(task);
}
}
do_some_other_stuff();
}
I know this code is poor on many levels (like exception handling) and there are much better approaches when it comes to task handling anyway - I'm just interested in one aspect:
I call my_list.empty()
outside the mutex scope (maybe to avoid locking my_mutex
in performance critical situations).
That smells bad and I'm not planning to do this - but I wonder what can really happen.empty()
returns bool
- can I assume at least this call to be safe?
Of course content can have changed after I call empty()
so I have to avoid race conditions which I do by again checking empty()
inside the mutex scope.
So my question is - what effects can this kind of code have in real world hypothetically regarding false positives, false negatives or even crashes?