[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Example of threads and concurrency?
From: |
Noam Postavsky |
Subject: |
Re: Example of threads and concurrency? |
Date: |
Sat, 18 Feb 2017 14:23:22 -0500 |
On Sat, Feb 18, 2017 at 1:43 PM, Eric Abrahamsen
<address@hidden> wrote:
>> I update the variable with a time-consuming/network-bound
>> computation. I want the computation to happen in a thread so it
>> doesn't block,
You're out of luck, only one thread runs at a time.
>> Is everything in the right place? It just occurs to me that If I put
>> `thread-join' at the bottom of `update-data-in-thread' then it will
>> effectively be synchronous after all! So I put that somewhere else, or I
>> don't call it at all.
Yes (although as I said above, there is no parallelism regardless).
>>
>> Other questions:
>>
>> 1. Other code just has to know that it can't touch
>> `important-data-variable' without holding `important-data-mutex',
>> right?
Yes.
>> 2. I want the timer to signal the thread to give up after ten seconds --
>> do I need to put anything in `update-important-data' that handles
>> that signal?
The thread needs to call something that would yield, otherwise the
cancelling signal call will never have a chance to be sent. The thread
doesn't need to handle the signal (assuming you're fine with just
quitting the thread).
>> 3. What do condition vars actually do? The manual has an example that
>> looks just like what I'm doing above:
>>
>> (with-mutex mutex
>> (setq global-variable (some-computation))
>> (condition-notify cond-var))
>>
>> What is cond-var doing here?
To unblock the other thread that is waiting for it (2 paragraphs up):
(with-mutex mutex
(while (not global-variable)
(condition-wait cond-var)))
>> It seems like both mutexes and cond-vars are there so other code knows
>> when to keep its hands off `important-data-variable', but I don't
>> understand how they're actually used.
They are used to synchronize between threads. But if your thread is
just doing a single computation and then ends, make-thread and
thread-join can be an alternative to them.