<sect1><title>Threads and Mutual Exclusion in Nickle</title>

<sect2><title>Basic threading</title>
<para>
Threads provide concurrent processing of calculations.
They are created with the <literal>fork</literal> operator, which spawns a child thread to evaluate its argument and returns it as a variable of the first-class type <literal>thread</literal>:
</para>
<synopsis>
fork <literal>expr</literal>
</synopsis>
<para>
The thread it returns is typically stored like this:
<informalexample><screen>
thread t = fork x!;
</screen></informalexample>
</para>
<para>
In the above example, <literal>fork</literal> immediately returns a thread, which is stored in <literal>t</literal>.
That thread will calculate the factorial of <literal>x</literal> in the background while the program continues; when the calculation is finished it will block and wait for the parent thread (the one that forked it) to kill, join, or otherwise recognize it.
</para>
<para>
<emphasis>Threads share names</emphasis>; if a thread changes the value of a variable, that change will occur in the other threads as well.
See Mutual exclusion below.
</para>
</sect2>

<sect2><title>Thread functions</title>
<para>
The builtin namespace Thread has functions for manipulating threads once they have been forked.
</para>

<sect3><title>Kill</title>
<synopsis>
int kill ( thread t, ... )
</synopsis>
<para>
Kills the threads it takes as arguments, regardless of whether or not they are finished, and returns the number of threads successfully killed. 
</para>
</sect3>

<sect3><title>Join</title>
<synopsis>
poly join ( thread t )
</synopsis>
<para>
Waits for thread <literal>t</literal> to finish and returns the value of its expression.
This is how to get the value back out of a thread.
Once joined, the thread will dissappear.
For example,
<informalexample><screen>
thread t = fork 1000!;
# something else...
printf("1000! = %d\n",Thread::join(t));
</screen></informalexample>
</para>
<para>
will execute 'something else' while <literal>t</literal> runs, then wait for it to complete and print out its value.
</para>
</sect3>

<sect3><title>Current</title>
<synopsis>
thread current ( )
</synopsis>
<para>
Returns the currently running thread. Note that things such as <literal>kill(current())</literal> and <literal>join(current())</literal> are allowed, although the former merely exits and the latter hangs forever; watch out for these errors.
</para>
</sect3>

<sect3><title>Priorities</title>
<synopsis>
int set_priority ( thread t, int i )
</synopsis>
<synopsis>
int get_priority ( thread t )
</synopsis>
<para>
Priorities determine how runtime is divided among threads; a thread with higher priority will always run before one with a lower priority.
<literal>set_priority</literal> sets the priority of <literal>t</literal> to <literal>i</literal> and returns the new priority.
<literal>get_priority</literal> returns the priority of thread <literal>t</literal>.
</para>
</sect3>

</sect2>

<sect2><title>Mutual exclusion</title>
<para>
Consider the following situation:
<informalexample><screen>
import Thread;

void function para() {
        printf("My next statement will be false.\n");
}

void function dox() {
        printf("My previous statement was true.\n");
}

thread t = fork para();
thread s = fork dox();
join(t);
join(s);
</screen></informalexample>
</para>
<para>
When run, this prints out the less than clear message
<informalexample><screen>
MMyy  nperxetv isotuast esmteantte mweinltl  wbaes  ftarlusee..
</screen></informalexample>
</para>
<para>
Why? Because the two threads are running simultaneously and take turns printing out their messages; the result is that they are interleaved unreadably.
The solution is in the builtin namespace Mutex.
A mutex is a first-class object which threads can use to coordinate conflicting sections of code.
Mutex defines the following functions:
</para>

<sect3><title>New</title>
<synopsis>
mutex new ( )
</synopsis>
<para>
Creates a new mutex and returns it.
</para>
</sect3>

<sect3><title>Acquire</title>
<synopsis>
bool acquire ( mutex m )
</synopsis>
<para>
<literal>acquire</literal> blocks until <literal>m</literal> is free, then locks it and returns true.
At the top of the conflicting code, each thread should acquire the mutex; since only one at a time can have it, they will take turns executing.
There is also a <literal>try_acquire</literal> that returns false immediately rather than blocking if <literal>m</literal> is in use, but it is deprecated.
</para>
</sect3>

<sect3><title>Release</title>
<synopsis>
void release ( mutex m )
</synopsis>
<para>
When the thread which owns a mutex leaves the conflicting section of code, it should call release to free it for the next thread to acquire it.
</para>
</sect3>

<sect3><title>Owner</title>
<synopsis>
mutex_owner owner ( mutex m )
</synopsis>
<para>
Returns the owner of <literal>m</literal>: either the thread which currently owns it or null if it is free.
</para>
</sect3>

</sect2>

<sect2><title>An example</title>
<para>
This is how the example above might work with mutual exclusion:
<informalexample><screen>
import Mutex;
import Thread;

mutex m = new();

void function para() {
        acquire(m);
        printf("My next statement will be false.\n");
        release(m);
}

void function dox() {
        acquire(m);
        printf("My previous statement was true.\n");
        release(m);
}

thread t = fork para();
thread s = fork dox();
join(t);
        join(s);
</screen></informalexample>
</para>
<para>
This prints out, as expected,
<informalexample><screen>
My next statement will be false.
My previous statement was true.
</screen></informalexample>
</para>
</sect2>

<sect2><title>Semaphores</title>
<para>
Nickle also has counting semaphores, implemented in the Semaphore namespace.
Semaphores are similar to mutexes, but have some number of threads that may run that isn't necessarily one, as it is with mutexes.
A semaphore with a count of one behaves just like a mutex.
</para>

<sect3><title>New</title>
<para>
Semaphores are created with <literal>new</literal>, which is unlike <literal>Mutex::new</literal> in that it takes an argument: the number of threads it will run simultaneously.
</para>
<synopsis>
semaphore new ( int c )
</synopsis>
</sect3>

<sect3><title>Wait and Signal</title>
<para>
Just as Mutexes are <literal>acquire</literal>d and <literal>release</literal>d, threads <literal>wait</literal> on semaphores and <literal>signal</literal> them when finished.
</para>
<synopsis>
void wait ( semaphore s )
</synopsis>
<synopsis>
void signal ( semaphore s )
</synopsis>
<para>
<literal>wait</literal> merely decrements the count of <literal>s</literal>, which starts with the initial value specified by <literal>new</literal>.
If the count, after the decrement, is positive, the thread continues to run; if it is negative, it blocks until the count becomes positive again.
This will occur when one of the running threads calls <literal>signal</literal>, which increments the count of <literal>s</literal> and wakes up another thread if any are waiting.
</para>
</sect3>

<sect3><title>Negative initial counts</title>
<para>
If <literal>new</literal> is called with a negative initial count, much of the meaning of the semaphore is inverted.
The count now refers to the number of threads that must wait until one can execute; that is, the first <literal>c</literal> threads will block, and the <literal>c</literal>+1th will execute.
</para>
</sect3>

<sect3><title>Why semaphores?</title>
<para>
Semaphores are useful in situations where several threads can run simultaneously, but not more than a certain number.
They would be great, for instance, to work in a licensing system, where each thread needs some command, but only a certain number may run at a given time.
</para>
</sect3>

<sect3><title>Be careful</title>
<para>
Semaphores, unlike mutexes, are very error-prone.
They are not <literal>owned</literal>, in the sense that mutexes are, and therefore do not check what threads are signalling or waiting on them.
Thus, situations like this are possible:
<informalexample><screen>
> import Semaphore;
> semaphore s = new(3);
> s  
semaphore 1 (3);
> wait(s);       
> s
semaphore 1 (2);
> wait(s);
> s
semaphore 1 (1);
> s
semaphore 1 (1)
> for(int i=0; i < 100; ++i)
+   signal(s);
> s
semaphore 1 (101)
> wait(s)
> s
semaphore 1 (100)
> 
</screen></informalexample>
</para>
<para>
Therefore, code must be written carefully so that threads do not signal the semaphore more than once, and only once they have waited on it.
</para>
</sect3>

</sect2>

</sect1>
