File: Threads.k

package info (click to toggle)
kaya 0.2.0-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,012 kB
  • ctags: 1,307
  • sloc: cpp: 6,691; haskell: 4,833; sh: 2,868; yacc: 768; makefile: 700; perl: 87
file content (82 lines) | stat: -rw-r--r-- 1,914 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/** -*-C-*-ish
    Kaya standard library
    Copyright (C) 2004, 2005 Edwin Brady

    This file is distributed under the terms of the GNU Lesser General
    Public Licence. See COPYING for licence.
*/

module Threads;

import Builtins;

%include "thread_glue.h";
%imported "thread_glue";
%link "pthread";

foreign "thread_glue.o" {
    "Terminate the current thread."
    public Void end() = endThread;

    Ptr docreateThread(fn func,arg fnarg) = createThread;
    Void dokillThread(Ptr tid) = killThread;
    a dowaitForThread(Ptr tptr) = waitForThread;
    Ptr docreateMutex() = createMutex;
    Void dolock(Ptr m) = lock;
    Void dounlock(Ptr m) = unlock;
}

"Thread id.
We parametrise threads over their function's return type. This is
to keep type safety; otherwise we
have to do some unsafe stuff with <em>waitForThread</em>.
Contains a pointer to internal data about the thread."
abstract data Thread<rettype> = Thread(Ptr tptr);

"Mutex.
Contains a pointer to internal data about the mutex."
abstract data Mutex = Mutex(Ptr mptr);

"Create a thread.
<em>fn</em> is the function which is executed by the thread, <em>arg</em>
is its argument. The return value of this function can be queried by 
<em>waitForThread</em>."
public Thread<b> create(b(a) fn, a arg)
{
    id = docreateThread(fn,arg);
    return Thread(id);
}

"Wait for a thread to terminate.
Returns the thread's return value."
public rettype waitFor(Thread<rettype> id)
{
    return dowaitForThread(id.tptr);
}

public Void kill(Thread<rettype> id)
{
    dokillThread(id.tptr);
}

"Create a mutex."
public Mutex mutex()
{
    m = docreateMutex();
    return Mutex(m);
}

"Lock a mutex.
All other threads which attempt to lock this mutex will have to wait
until it is unlocked."
public Void lock(Mutex m)
{
    dolock(m.mptr);
}

"Unlock a mutex.
Allows other threads to lock the mutex."
public Void unlock(Mutex m)
{
    dounlock(m.mptr);
}