Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2007-03-26 15:55:19


On Mar 26, 2007, at 3:24 PM, Peter Dimov wrote:

> Or, stated differently,
>
> Why should a thread::cancel that is declared non-const necessarily
> be made
> thread and sharing unsafe?

The sole-ownership model generally implies that only one thread has
access to the std::thread (i.e. like std::fstream to the file on disk,
or lock<mutex> to the mutex.

There are somethings which *must* be thread safe anyway:

t.cancel() must be made safe with respect to
this_thread::cancellation_requested() since we have one thread writing
to the same value that another thread is trying to read.

t.cancellation_requested() must be thread safe with respect to the
innards of this_thread::cancellation_point() for the same reasons but
in reverse (the latter is writing while the former is reading).

However I don't want to add cost to support idioms which are
inherently unsafe in the pthread model anyway, for example:

std::thread t(f); // global

thread A thread B
t.join() t.cancel()

In pthreads this is a race. Bad things can happen if thread A gets
there first. If an implementation of std::thread happens to tolerate
this race, I have no problem with that. But I don't want to require
all implementations to add extra synchronization to make this race
well defined. N2184 is attempting to just model pthreads semantics.

Alternatively if we have:

thread A thread B
t.cancel() t.cancel()

then this should be a harmless race, both in pthreads and in N2184.
The implementation is already having to use atomics (or whatever) to
set the cancellation pending flag to protect it against reads in the t
thread. But:

thread A thread B
t.detach() t.cancel()

is again a race condition in both pthreads and N2184 (N2184 does a
lousy job of clarifying all this).

So bottom line: N2184 isn't aiming to go out of its way to make
sharing unsafe. It is attempting to add just enough cost to support
pthreads semantics and no more.

-Howard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk