[plt-scheme] Threads in embedded MzScheme

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Thu Jun 5 08:52:18 EDT 2003

At 05 Jun 2003 00:40:47 +0200, Daniel K. Skovenborg wrote:
> I wish to use thread that all can call scheme_ functions (only
> possible through MzScheme's threads, right?).

Right.

> But what do I do with MzScheme threads? Should I do like this?:
> 
>   Scheme_Object *sfoo = scheme_make_prim_w_arity(&foo, "foo", 0, 0);
>   scheme_thread(sfoo, scheme_config);

Pass scheme_make_config() for the second argument, otherwise correct.

> 2.
> I also need some sort of mutexes because the threads should be able to
> access the same data (also C-variables!).
> 
> As far as I can see, I should use semaphores to do the job, but I don't
> know if I have understood semaphores correctly. Is the following right?:
> You can use semaphores as a replacement for mutexes because it's a sort
> of thread-safe variable. So if I want a "mutex" for a variable foo i
> create semaphore bar with the initial value 1. When I wan't to change
> foo, I call (semaphore-wait bar) (or use scheme_apply in C) which will
> return if bar is 1 and decrement it to 0. Now I change the variable and
> thereafter call (semaphore-post bar). So bar i 0 if another thread is
> changing foo and (semaphore-wait bar) will block until the other thread
> is done and increment bar to 1.

That's correct...

> Or is it not necessary protect variables because MzScheme contols the
> whole thing more that OS threads does?

That's probably right. If you access the variable only through a
C-implemented function, and your function doesn't call anything named
scheme_... while modifying the variable, then no thread switch is
possible and the variable is implicitly synchronized.

> 3.
> That SCHEME_USE_FUEL macro looks sort of important, but I don't know
> when and why to use it. Inside MzScheme (p. 30) gives an example of a
> function constantly making a new pair from an indeks in a vector. Each
> loop calls SCHEME_USE_FUEL(1). Does it do this to let other threads do
> their job while the function is accessing scheme-variables or
> scheme-functions

It potentially swaps in other threads immediately. So if you put this
inside a loop, and the loop doesn't otherwise use scheme_... functions,
then this is the only point where other threads will run.


Actually, most scheme_... functions won't let other threads run. For
example, scheme_intern_symbol() and scheme_make_string() won't. In
contract, scheme_apply() will all other threads to run.

The documentation doesn't say which functions allow thread switches,
and it should --- especially in cases like scheme_intern_symbol(). I'm
sure that MrEd, at least, relies on scheme_intern_symbol() and
scheme_make_thread() not swapping treads.

I'll work on the docs.

Matthew



Posted on the users mailing list.