[plt-scheme] Threads in embedded MzScheme

From: Daniel K. Skovenborg (waldeinburg at yahoo.com)
Date: Wed Jun 4 18:40:47 EDT 2003

I'm having some troubles figuring out how to use threads in embedded
MzScheme (I'm a newbie). So here's 3 question:

I wish to use thread that all can call scheme_ functions (only
possible through MzScheme's threads, right?).

Inside MzScheme don't seem very beginner-friendly because it doesn't
give complete documentation for all functions, så I don't know how to
use the function "scheme_thread" that creates the thread.

So lets say that I wan't to make a thread, that runs the C function foo
that needs no parameters. Normally I would use the SDL-function
(ordinary OS thread) "SDL_CreateThread(int (*fn)(void *), void *data)"
like this

  SDL_CreateThread(&foo, NULL);

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);

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.

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

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(which brings me back to the question about the
necessity of mutexes again)?

Posted on the users mailing list.