Threading Questions

bitwise via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 5 14:25:13 PDT 2015


On Monday, 5 October 2015 at 20:18:18 UTC, Laeeth Isharc wrote:
> On Monday, 5 October 2015 at 17:40:24 UTC, bitwise wrote:
>> You may be right. I wrote a simple download manager in D using 
>> message passing. It was a little awkward at first, but in 
>> general, the spawn/send/receive API seems very intuitive. It 
>> feels awkward because the data you're working with is out of 
>> reach, but I guess it's safer that way.
>
> Any possibility of a blog post on your experience of doing so ? 
> ;)  [I should start writing some directly, but for time being, 
> until I have my blog up and running again, I write from time to 
> time on Quora].  A few minutes of writing now and then can have 
> a remarkably big impact as well as clarifying your own 
> thoughts, and the time invested is amply repaid, even viewed 
> from a narrowly self-interested perspective.

Unfortunately, my time is limited right now. I do have another 
project, which I've decided will either be finished or discarded 
by the dawn of 2016. So in the near future, I should have more 
time for other things.

> I had same experience with learning message passing.  Feels 
> like learning to eat with chopsticks in the beginning, but soon 
> enough it feels much more civilised when it's the right tool 
> for the job.

I like the way my Worker class works because when I don't need 
the thread anymore, I can simply discard the object that 
represents the thread. As long as the Worker object is higher up 
on the stack than anything it's working on, all is well, and the 
concept of spawn/join is not visible while programming. This 
works out ok, because while the jobs I'm doing are slow enough to 
make a UI thread lag, they aren't long-running enough to where 
waiting for the Worker's thread to join in the destructor becomes 
a problem. There may be a small lag as the Worker's destructor 
waits for the last job to finish and the thread to join, but it's 
only happens once in the lifetime of the worker, so it's not a 
big deal.

If care is not taken, the above could be subject to these 
problems:
1) shared memory corruption
2) worker accessing dead memory if it's placed on the stack below 
what it's working on
3) queueing a long running task could freeze the program on 
~Worker()

If you're moving or copying data into a thread, then returning 
the result(which can be ignored) I think most of the above can be 
solved.

It's still a bit foreign to me though, and C++ has no such 
construct yet afaik. I read a bit about std::future and so on, 
but I'm not sure if they're standard yet. The biggest blocker 
though, is that the project I'm using that Worker class in is a 
Unity3D plugin. They only very recently updated their iOS libs to 
allow libc++ > 98....

     Bit


More information about the Digitalmars-d-learn mailing list