aboutsummaryrefslogtreecommitdiff
path: root/api/channels.md
blob: dbb6707a4a2b32e5ef28a90f46bf515ba3b31037 (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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# Channels

Channels are a thread-safe message queue for communicating between threads,
although they can also be used as a general-purpose queue.

## Syntax

The syntax to create a channel is `|:T|`, where `T` is the type that will be
passed through the channel. You can also specify a maximum size for the
channel, which will cause giving to block until the recipient has gotten from
the channel if the maximum size is reached.

```tomo
channel := |:Int|
channel:give(10)
channel:give(20)
>> channel:get()
= 10
>> channel:get()
= 20

small_channel := |:Int; max_size=5|
```

## Channel Methods

### `give`

**Description:**  
Adds an item to the channel.

**Usage:**  
```markdown
give(channel:|T|, item: T) -> Void
```

**Parameters:**

- `channel`: The channel to which the item will be added.
- `item`: The item to add to the channel.

**Returns:**  
Nothing.

**Example:**  
```markdown
>> channel:give("Hello")
```

---

### `give_all`

**Description:**  
Adds multiple items to the channel.

**Usage:**  
```markdown
give_all(channel:|T|, items: [T]) -> Void
```

**Parameters:**

- `channel`: The channel to which the items will be added.
- `items`: The array of items to add to the channel.

**Returns:**  
Nothing.

**Example:**  
```markdown
>> channel:give_all([1, 2, 3])
```

---

### `get`

**Description:**  
Removes and returns an item from the channel. If the channel is empty, it waits until an item is available.

**Usage:**  
```markdown
get(channel:|T|) -> T
```

**Parameters:**

- `channel`: The channel from which to remove an item.

**Returns:**  
The item removed from the channel.

**Example:**  
```markdown
>> channel:get()
= "Hello"
```

---

### `clear`

**Description:**  
Removes all items from the channel.

**Usage:**  
```markdown
clear(channel:|T|) -> Void
```

**Parameters:**

- `channel`: The mutable reference to the channel.

**Returns:**  
Nothing.

**Example:**  
```markdown
>> channel:clear()
```

---

### `view`

**Description:**  
Returns a list of all items currently in the channel without removing them.

**Usage:**  
```markdown
channel:view() -> [T]
```

**Parameters:**

- `channel`: The channel to view.

**Returns:**  
An array of items currently in the channel.

**Example:**  
```markdown
>> channel:view()
= [1, 2, 3]
```