[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Gforth pthreads support

From: David Kuehling
Subject: Gforth pthreads support
Date: Sun, 25 Jul 2021 05:26:29 +0000


I'm just starting to write multi-threaded Gforth programs for the first
time and stumbled over what looks like an inconsistency in the API [1]:

While I can start new threads using newtask and pass/activate, there is
no obvious way to synchronize the main thread against concurrently
running threads.  I.e. if I naively run one ore more workers using

  : spawn-workunit
     stacksize4 newtask4 pass
     \ work to do

Than the main program will just continue until BYE, which will not wait
on any of the active threads (and maybe cause some crashing when Gforth
attempts to exit while threads are still accessing various data).

The API seems to be built to allow message passing back to the main
thread using <event ... event>.  However, there is no documented way to
reference the main thread when doing so.  It seems that the otherwise
undocumented word UP@ can be used to reference the main thread, so by
trial&error (and looking at implementation and some example code) I
found this code to be doing what I need:

  VARIABLE spawned  0 spawned !
  event:  unspawn  -1 spawned +! ;
  up@ CONSTANT main-task

  : spawn-workunit
     1 spawned +!
     stacksize4 newtask4 pass
     \ work to do
     <event unspawn main-task event>

  : join
     \ event loop until all threads done
     BEGIN spawned @ WHILE stop REPEAT ;

Also the documentation is not exactly clear on what happens when a
function that started a thread via activate / pass exits.  Looking at
pthread.fs I think the thread actually exits cleanly, but as Gforth
mixes pthread semantics with some non-pthreads message passing API,
reading the manual I feared it may enter the event loop on EXIT.

Note also, that for some reason, the glosgen comments for <event &
friends are missing from the manual.

Other than that, I'm quite happy with the <event API.  Having dealt with
a deadlocks in huge C++ applications, I really appreciate being able to
fully handle synchronization using message-passing only.



PS: looking at silk.fs, I may have been reinventing the wheel here.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]