A cooperative multitasker can ensure that there is no other task
interacting between two invocations of pause
. Pthreads however
are really concurrent tasks (at least on a multi-core CPU), and
therefore, several techniques to avoid conflicts when accessing the same
resources.
Semaphores can only be aquired by one thread, all other threads have to wait until the semapohre is released.
semaphore
( "name" – ) gforth-experimental “semaphore”
create a named semaphore name
name execution: ( – semaphore )
lock
( semaphore – ) gforth-experimental “lock”
lock the semaphore
unlock
( semaphore – ) gforth-experimental “unlock”
unlock the semaphore
The other approach to prevent concurrent access is the critical section. Here, we implement a critical section with a semaphore, so you have to specify the semaphore which is used for the critical section. Only those critical sections which use the same semaphore are mutually exclusive.
critical-section
( xt semaphore – ) gforth-experimental “critical-section”
Execute xt while locking semaphore. After leaving xt, semaphore is unlocked even if an exception is thrown.