forked from doublec/factor-articles
-
Notifications
You must be signed in to change notification settings - Fork 1
/
channels.tex
53 lines (40 loc) · 1.68 KB
/
channels.tex
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
\chapter{Channels}\label{channels}
Rob Pike gave a talk at Google about the NewSqueak programming
language, and specifically how it's concurrency features
work. NewSqueak uses channels and is based on the concepts of
Communicating Sequential Processes.
Factor has a 'channels' vocabulary that lets you do similar things.
\wordtable{
\vocabulary{channels}
\ordinaryword{<channel>}{<channel> ( -- channel )}
\ordinaryword{to}{to ( value channel -- )}
\ordinaryword{from}{from ( channel -- value )}
}
The \texttt{<channel>} word creates a channel that threads can send data to and
receive data from. The \texttt{to} word sends data to a channel. It is a
synchronous send and blocks waiting for a receiver if there is
none. The \texttt{from} word receives data from a channel. It will block if
there is no sender.
There can be multiple senders waiting, and if a thread then receives
on the channel, a random sender will be released to send its
data. There can also be multiple receivers blocking. A random one is
selected to receive the data when a sender becomes available.
Here is the `counter' example ported from NewSqueak:
\begin{verbatim}
USING: channels fry threads ;
: (counter) ( channel n -- )
[ swap to ] [ 1 + (counter) ] 2bi ;
: counter ( channel -- )
2 (counter) ;
: counter-test ( -- n1 n2 n3 )
<channel> dup '[ _ counter ] "counter" spawn drop
[ from ] [ from ] [ from ] tri ;
counter-test . . .
=> 2
3
4
\end{verbatim}
Given a channel, the \texttt{counter} word will send numbers to it,
incrementing them by one, starting from two. \texttt{counter-test} creates a
channel, spawns a process to run \texttt{counter}, and then receives a few
values from the channel.