Author Topic: jss::synchronized_value  (Read 52514 times)

py

  • Newbie
  • *
  • Posts: 1
    • View Profile
jss::synchronized_value
« 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?

Anthony Williams

  • Administrator
  • Full Member
  • *****
  • Posts: 103
    • View Profile
    • just::thread C++ Thread Library
Re: jss::synchronized_value
« Reply #1 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.
    }
}