just::thread Support Forum

General Category => General Discussion about just::thread => Topic started by: py on April 23, 2013, 11:41:40 AM

Title: jss::synchronized_value
Post by: py on April 23, 2013, 11:41:40 AM
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?
Title: Re: jss::synchronized_value
Post by: Anthony Williams on April 23, 2013, 12:13:46 PM
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: [Select]
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.
    }
}