General Category > General Discussion about just::thread

jss::synchronized_value

(1/1)

py:
In the example given:

jss::synchronized_value<std::string> s;

void foo(){
    if(s->empty()){
        *s =  "hello";
    }
}

Is there not a race condition between checking for empty and then assigning to s? Presumably another thread could write to s after the empty check but before the assignment? Or does synchronized_value somehow protect against this?

Anthony Williams:
Yes, there's a potential race between the test and the set. It's "safe" in the sense that the mutex is held across each access, but it might overwrite a change made by another thread.

This is a dummy example. Probably not a very good one  :(

jss::update_guard is the companion to jss::synchronized_value that allows safe accesses across multiple statements:


--- Code: ---jss::synchronized_value<std::string> sv;

void bar(){
    jss::update_guard<std::string> guard(sv);
    if(guard->empty()){
        *guard="hello"; // no potential for a race here.
    }
}

--- End code ---





Navigation

[0] Message Index

Go to full version