tomo/docs/threads.md

114 lines
1.7 KiB
Markdown
Raw Normal View History

2024-08-18 15:23:32 -07:00
# Threads
Tomo supports POSIX threads (pthreads) through the `Thread` type. The
recommended practice is to have each thread interact with other threads only
2025-01-02 13:29:21 -08:00
through [mutex-guarded datastructures](mutexed.md).
2024-08-18 15:23:32 -07:00
## Thread Methods
2025-03-04 21:21:30 -08:00
- [`func cancel(thread: Thread)`](#`cancel)
- [`func detach(thread: Thread)`](#`detach)
- [`func join(thread: Thread)`](#`join)
- [`func new(fn: func(->Void) -> Thread)`](#`new)
### `cancel`
2024-08-18 15:23:32 -07:00
**Description:**
2025-03-04 21:21:30 -08:00
Requests the cancellation of a specified thread.
2024-08-18 15:23:32 -07:00
**Signature:**
2024-08-18 15:23:32 -07:00
```tomo
2025-03-04 21:21:30 -08:00
func cancel(thread: Thread)
2024-08-18 15:23:32 -07:00
```
**Parameters:**
2025-03-04 21:21:30 -08:00
- `thread`: The thread to cancel.
2024-08-18 15:23:32 -07:00
**Returns:**
2025-03-04 21:21:30 -08:00
Nothing.
2024-08-18 15:23:32 -07:00
**Example:**
```tomo
2025-03-04 21:21:30 -08:00
>> thread:cancel()
2024-08-18 15:23:32 -07:00
```
---
2025-03-04 21:21:30 -08:00
### `detach`
2024-08-18 15:23:32 -07:00
**Description:**
2025-03-04 21:21:30 -08:00
Detaches a specified thread, allowing it to run independently.
2024-08-18 15:23:32 -07:00
**Signature:**
2024-08-18 15:23:32 -07:00
```tomo
2025-03-04 21:21:30 -08:00
func detach(thread: Thread)
2024-08-18 15:23:32 -07:00
```
**Parameters:**
2025-03-04 21:21:30 -08:00
- `thread`: The thread to detach.
2024-08-18 15:23:32 -07:00
**Returns:**
Nothing.
**Example:**
```tomo
2025-03-04 21:21:30 -08:00
>> thread:detach()
2024-08-18 15:23:32 -07:00
```
### `join`
**Description:**
Waits for a specified thread to terminate.
**Signature:**
2024-08-18 15:23:32 -07:00
```tomo
func join(thread: Thread)
2024-08-18 15:23:32 -07:00
```
**Parameters:**
- `thread`: The thread to join.
**Returns:**
Nothing.
**Example:**
```tomo
>> thread:join()
```
---
2025-03-04 21:21:30 -08:00
### `new`
2024-08-18 15:23:32 -07:00
**Description:**
2025-03-04 21:21:30 -08:00
Creates a new thread to execute a specified function.
2024-08-18 15:23:32 -07:00
**Signature:**
2024-08-18 15:23:32 -07:00
```tomo
2025-03-04 21:21:30 -08:00
func new(fn: func(->Void) -> Thread)
2024-08-18 15:23:32 -07:00
```
**Parameters:**
2025-03-04 21:21:30 -08:00
- `fn`: The function to be executed by the new thread.
2024-08-18 15:23:32 -07:00
**Returns:**
2025-03-04 21:21:30 -08:00
A new `Thread` object representing the created thread.
2024-08-18 15:23:32 -07:00
**Example:**
```tomo
2025-03-04 21:21:30 -08:00
>> jobs := |Int|
>> results := |Int|
>> thread := Thread.new(func():
repeat:
input := jobs:get()
results:give(input + 10
)
= Thread<0x12345678>
>> jobs:give(10)
>> results:get()
= 11
2024-08-18 15:23:32 -07:00
```