Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2007-03-26 14:25:24


On Mar 26, 2007, at 2:04 PM, Peter Dimov wrote:

> Howard Hinnant wrote:
>
>> Fair point. Perhaps we should go back to a more fundamental
>> question:
>>
>> std::thread t(f);
>> ...
>> t.cancel(); // Logically is this a const or non-const operation on
>> the thread executing t/f?
>
> I prefer to first ask "does it matter"? If you can't observe the
> cancelation
> state of t and if you are assured that t.cancel is valid no matter
> what else
> is going on with t, what difference does a const/non-const label
> make to the
> external observer?
>
> (Internally there is a flag being set, of course.)

I believe it matters because other threads can detect whether the
child thread has been canceled or not. Canceled may be a valid
state. But it is a different and detectable state. Here's a simple
HelloWorld demonstrating it:

#include "thread"
#include <iostream>

std::thread t;

std::mutex mut;
std::condition<std::exclusive_lock<std::mutex> > cv;

bool work_done = false;

void f()
{
     std::this_thread::sleep(2);
     {
     std::exclusive_lock<std::mutex> lk(mut);
     work_done = true;
     }
     cv.notify_all();
}

void f2()
{
     std::this_thread::sleep(1);
// t.cancel();
}

int main()
{
     t = std::thread(f);
     std::thread t2(f2);
     std::exclusive_lock<std::mutex> lk(mut);
     while (!work_done)
         cv.wait(lk);
     std::cout << "Success!\n";
}

This prints out "Success!" as it is now. But if you comment out
"t.cancel()" in f2 then main hangs forever. f2 did something
logically non-const to the separate thread f which in turn caused the
main thread to react differently. This seems to me like f2 is doing
something non-const.

-Howard


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