Thread-safety of assignment of std::exception_ptr (C++0x)

S

Scott Meyers

Suppose I run a couple of functions in parallel, catching an exception if either
throws. If both throw, I want to catch one of the exceptions, but I don't care
which one. I might try this:

std::exception_ptr xp;

std::async([&]{
try { doThis(); }
catch(...) { xp = std::current_exception(); }
});

std::async([&]{
try { doThat(); }
catch(...) { xp = std::current_exception(); }
});

if (xp) {
// at least one of the tasks above threw
}

This can work only if assignment to xp (i.e., a std::exception_ptr object) is
thread-safe. I see no such guarantee in draft C++0x, but I'm hoping I'm
overlooking something. Is there any reason to believe that assignment to a
std::exception_ptr object is thread-safe?

Thanks,

Scott
 
B

Balog Pal

Scott Meyers said:
This can work only if assignment to xp (i.e., a std::exception_ptr object)
is thread-safe. I see no such guarantee in draft C++0x, but I'm hoping
I'm overlooking something. Is there any reason to believe that assignment
to a std::exception_ptr object is thread-safe?

17.6.3.10 is pretty explicit about the baseline with standard library types.
(race condition == UB unless explicitly allowed for the type/operation).

As I read 18.8.5 it defines exception_ptr and there is no mention of that
allowance.

I interpret that as your concern being valid, and you shall protect your
shared exception_ptr from race to have defined behavior.

Originally I was to say that it may be an overlook worth a DR, but thinking
again, why this case should be special? And why you expect it to be more
thread safe than say if you had a shared vector<string> and had
push_back(ex.what()) in the catch handler? Or just increment a simple int
hing to get proper count?

Do you see a blocking factor to use any of the usual access-serialization
measures in your situation?
 
S

Scott Meyers

17.6.3.10 is pretty explicit about the baseline with standard library types.
(race condition == UB unless explicitly allowed for the type/operation).

As I read 18.8.5 it defines exception_ptr and there is no mention of that
allowance.

I interpret that as your concern being valid, and you shall protect your shared
exception_ptr from race to have defined behavior.

I agree, thanks for the relevant standard sections.

Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top