A Refcounted Array Type
Michel Fortin via Digitalmars-d
digitalmars-d at puremagic.com
Thu Feb 26 15:09:38 PST 2015
On 2015-02-26 21:07:26 +0000, Andrei Alexandrescu said:
> On 2/26/15 12:54 PM, deadalnix wrote:
>> On Thursday, 26 February 2015 at 16:57:51 UTC, Andrei Alexandrescu wrote:
>>> On 2/26/15 8:51 AM, Steven Schveighoffer wrote:
>>>> As talked about before, running dtors in the originating thread can
>>>> solve this problem.
>>>
>>> Yah, that will solve the nonatomic reference counting. What do you
>>> think about http://forum.dlang.org/thread/mcllre$1abs$1@digitalmars.com?
>>>
>>> Andrei
>>
>> class BazingaException : Exception {
>>
>> RefCount!Stuff reallyImportantStuff;
>>
>> // ...
>>
>> }
>>
>> void main() {
>> auto t = new Thread({
>> RefCount!Stuff s = ...;
>> throw new BazingaException(s);
>> });
>>
>> t.start();
>> t.join();
>> }
>
> Could you please walk me through what the matter is here. Thanks. -- Andrei
The exception is thrown by t.join() in another thread, after the
originating thread died. Thus, obviously, it cannot be destructed in
the originating thread as stated above. But everyone already know that.
But the example doesn't make one problem quite clear: Unless the GC
destroys the exception in the thread join() was called, there can be a
race. That's because join() moves the exception to another thread, and
the thread that now owns the exception could make copies of that
reallyImportantStuff and access the counter beyond the exception's
lifetime. So it turns out that the GC heap needs call the exception's
destructor in the thread calling join() to avoid races.
Additionally, if the old thread has leftover objects still not yet
collected, they'll need to be destroyed in the thread calling join()
too. Otherwise you might get races when the exception is destroyed.
So you could solve all that by changing of ownership for things
originating from the worker thread to the thread that is calling
join(). Or if no one calls join(), then you can destroy objects
originating from the dead thread in any thread, as long as they are all
destroyed *in the same thread* (because objects originating from the
same thread might all points to the same thread-local reference counts).
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list