handling shared objects
Steven Schveighoffer
schveiguy at gmail.com
Mon Nov 26 16:27:23 UTC 2018
On 11/26/18 10:37 AM, Alex wrote:
> On Monday, 26 November 2018 at 15:26:43 UTC, Steven Schveighoffer wrote:
>>
>> Well, if you want to run calculations in another thread, then send the
>> result back to the original, you may be better off sending the state
>> needed for the calculation to the worker thread, and receiving the
>> result back via the messaging system.
>
> How to do this, if parts of the state are statically saved in a type?
For instance, with your toy example, instead of saving the D[] as a
static instance to share with all threads, use idup to make a complete
copy, and then send that array directly to the new thread via spawn.
When the result is done, instead of sending a bool to say it's complete,
send the answer.
Sending an immutable copy is the easiest way to ensure you have no
races. It may be more expensive than you want to make a deep copy of
something, but probably less expensive than the headache of creating a
non-debuggable monster race condition.
>
>> Note that if you want to do it without safety in place, you can use
>> the Thread class in core.thread which has no requirements for data to
>> be immutable or shared. But you have to be even more careful about how
>> you access the data.
>>
>
> Ah... ok. But then, I will prefer to mark the appropriate parts as
> shared, I think...
Right :)
Threading is always very difficult to get right, and usually very
difficult to find errors when you get it wrong. I remember working with
pthreads about 20 years ago in a C++ project, and having a data race
that caused a hang once every *2 weeks*. It took insane amounts of
printouts and logging to figure out exactly why it happened (and the
cycle was 2 weeks roughly), and the cause was (I think, not 100% sure) a
place where a lock should have been but wasn't used.
-Steve
More information about the Digitalmars-d-learn
mailing list