summaryrefslogtreecommitdiff
path: root/examples/pc.nl
blob: 1382e0dbc290180a4a3de8d433e9748297d1b51f (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class label_queue
{
    queue:		array[label];
    head, tail:		int32;

    ensure ()
    {
	if (queue == null)
	{
	    queue = new array[label] (256);
	    head = tail = 0;
	}
    }
    
    push_back (l: label)
    {
	ensure();

	queue[(tail++) & 0xff] = l;
    }
    
    pop_head() -> label
    {
	ensure();

        return queue[(head++) & 0xff];
    }
    
    is_empty() -> bool
    {
	return head == tail;
    }
};

run_list := new label_queue();

thread_yield()
{
    run_list.push_back (this_thread);

    goto run_list.pop_head();
    
@this_thread:
}

thread_fork (child: fn())
{
    run_list.push_back (this_thread);
    child();
    goto run_list.pop_head();
    
@this_thread:
}

thread_exit()
{
    if (!run_list.is_empty())
	goto run_list.pop_head();
    else
	goto process_exit;
}

/*
 * Demonstration of cooperative thread system
 */

n_done: int32;

t1 ()
{
    thread_fork (fn () { t2 ("t2:1"); });
    
    for (i := 0; i < 3; ++i)
    {
	print "t1";
	
	if (i % 2 == 0)
	    thread_yield();
    }

    print "done: t1, forking some more t2s";
    thread_fork (fn() { t2 ("t2:2"); });
    thread_fork (fn() { t2 ("t2:3"); });
    n_done++;
    thread_exit();
}

t2 (name: string)
{
    for (i := 0; i < 7; ++i)
    {
	print name, 12;
	
	if (i % 2 == 0)
	    thread_yield();
    }

    print "done:", name;
    n_done++;
    thread_exit();
}

n_done = 0;

/* Fork thread 1 */

thread_fork (t1);

/* Exit main thread */
thread_exit ();

/* And spin forever if we ever get here (which we shouldn't) */
for (;;)
    print "We shouldn't get here";

/* Once the last thread exits, it will go here */
@process_exit:
   print n_done, "threads finished";