Documentation
¶
Overview ¶
Package async is a library for asynchronous programming.
Since Go has already done a great job in bringing green/virtual threads into life, this library only implements a single-threaded Executor type, which some refer to as an async runtime. One can create as many Executors as they like.
While Go excels at forking, async, on the other hand, excels at joining.
Use Case #1: Fan-in Executing Code From Various Goroutines ¶
Wanted to execute pieces of code from various goroutines in a single-threaded way?
An Executor is designed to be able to run Tasks spawned in various goroutines sequentially. This comes in handy when one wants to do a series of operations on a single thread, for example, to read or update states that are not safe for concurrent access, to write data to the console, to update one's user interfaces, etc.
No backpressure alert. Task spawning is designed not to block. If spawning outruns execution, an Executor could easily consume a lot of memory over time. To mitigate, one could introduce a semaphore per hot spot.
Use Case #2: Event-driven Reactiveness ¶
A Task can be reactive.
A Task is spawned with a Coroutine to take care of it. In this user-provided function, one can return a specific Result to tell a Coroutine to watch and await some Events (e.g. Signal, State and Memo, etc.), and the Coroutine can just re-run the Task whenever any of these Events notifies.
This is useful when one wants to do something repeatedly. It works like a loop. To exit this loop, just return a Result that ends the Coroutine from within the Task function. Simple.
Use Case #3: Easy State Machines ¶
A Coroutine can also switch from one Task to another, just like a state machine can transit from one state to another. This is done by returning another specific Result from within a Task function. A Coroutine can switch from one Task to another until a Task ends it.
Spawning Async Tasks vs. Passing Data over Go Channels ¶
It's not recommended to have channel operations in an async Task for a Coroutine to do, since they tend to block. For an Executor, if one Coroutine blocks, no other Coroutines can run. So instead of passing data around, one would just handle data in place.
One of the advantages of passing data over channels is to be able to reduce allocation. Unfortunately, async Tasks always escape to heap. Any variable they captured also escapes to heap. One should always stay alert and take measures in hot spot, like repeatedly using a same Task.
Example ¶
This example demonstrates how to spawn Tasks with different paths. The lower path, the higher priority. This example creates a Task with path "aa" for additional computations and another Task with path "zz" for printing results. The former runs before the latter because "aa" < "zz".
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
// Create an Executor.
var myExecutor async.Executor
// Set up an autorun function to run an Executor automatically whenever a Coroutine is spawned or resumed.
// The best practice is to pass a function that does not block. See Example (NonBlocking).
myExecutor.Autorun(myExecutor.Run)
// Create two States.
s1, s2 := async.NewState(1), async.NewState(2)
// Although States can be created without the help of Executors,
// they might only be safe for use by one and only one Executor because of data races.
// Without proper synchronization, it's better only to spawn Coroutines to read or update States.
var sum, product async.State[int]
myExecutor.Spawn("aa", func(co *async.Coroutine) async.Result { // The path of co is "aa".
co.Watch(s1, s2) // Let co depend on s1 and s2, so co can re-run whenever s1 or s2 changes.
sum.Set(s1.Get() + s2.Get())
product.Set(s1.Get() * s2.Get())
return co.Await() // Awaits signals or state changes.
})
// The above Task re-runs whenever s1 or s2 changes. As an example, this is fine.
// In practice, one should probably use Memos to avoid unnecessary recomputations. See Example (Memo).
op := async.NewState('+')
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result { // The path of co is "zz".
co.Watch(op)
fmt.Println("op =", "'"+string(op.Get())+"'")
switch op.Get() {
case '+':
// The path of an inner Coroutine is relative to its outer one.
co.Spawn("sum", func(co *async.Coroutine) async.Result { // The path of inner co is "zz/sum".
fmt.Println("s1 + s2 =", sum.Get())
return co.Await(&sum)
})
case '*':
co.Spawn("product", func(co *async.Coroutine) async.Result { // The path of inner co is "zz/product".
fmt.Println("s1 * s2 =", product.Get())
return co.Await(&product)
})
}
return co.Await()
})
fmt.Println("--- SEPARATOR ---")
// The followings create several Tasks to mutate States.
// They share the same path, "/", which is lower than "aa" and "zz".
// Remember that, the lower path, the higher priority.
// Updating States should have higher priority, so that when there are multiple update Tasks,
// they can run together before any read Task.
// This reduces the number of reads that have to react on update.
myExecutor.Spawn("/", async.Do(func() {
s1.Set(3)
s2.Set(4)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
op.Set('*')
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(5)
s2.Set(6)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(7)
s2.Set(8)
op.Set('+')
}))
}
Output: op = '+' s1 + s2 = 3 --- SEPARATOR --- s1 + s2 = 7 --- SEPARATOR --- op = '*' s1 * s2 = 12 --- SEPARATOR --- s1 * s2 = 30 --- SEPARATOR --- op = '+' s1 + s2 = 15
Example (Chain) ¶
This example demonstrates how to chain multiple Tasks together to be worked on in sequence by a Coroutine.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", async.Chain(
func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(first)")
if v < 3 {
return co.Await()
}
return co.Switch(func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(switched)")
if v < 5 {
return co.Await()
}
return co.End()
})
},
func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(second)")
if v < 7 {
return co.Await()
}
return co.End()
},
))
for i := 1; i <= 9; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 9.
}
Output: 0 (first) 1 (first) 2 (first) 3 (first) 3 (switched) 4 (switched) 5 (switched) 5 (second) 6 (second) 7 (second) 9
Example (Conditional) ¶
This example demonstrates how a Task can conditionally depend on a State.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
s1, s2, s3 := async.NewState(1), async.NewState(2), async.NewState(7)
myExecutor.Spawn("aa", func(co *async.Coroutine) async.Result {
co.Watch(s1, s2) // Always depends on s1 and s2.
v := s1.Get() + s2.Get()
if v%2 == 0 {
co.Watch(s3) // Conditionally depends on s3.
v *= s3.Get()
}
fmt.Println(v)
return co.Await()
})
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
myExecutor.Spawn("/", async.Do(func() { s1.Set(s1.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() }))
myExecutor.Spawn("/", async.Do(func() { s2.Set(s2.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
}
Output: 3 28 28 5
Example (ConditionalMemo) ¶
This example demonstrates how a Memo can conditionally depend on a State.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
s1, s2, s3 := async.NewState(1), async.NewState(2), async.NewState(7)
m := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2) // Always depends on s1 and s2.
v := s1.Get() + s2.Get()
if v%2 == 0 {
co.Watch(s3) // Conditionally depends on s3.
v *= s3.Get()
}
s.Set(v)
})
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(m)
fmt.Println(m.Get())
return co.Await()
})
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
myExecutor.Spawn("/", async.Do(func() { s1.Set(s1.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() }))
myExecutor.Spawn("/", async.Do(func() { s2.Set(s2.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
}
Output: 3 28 28 5
Example (Defer) ¶
This example demonstrates how to add a function call before a Task re-runs, or after a Task ends.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
co.Defer(func() { fmt.Println(v, myState.Get()) })
if v < 3 {
return co.Await()
}
return co.End()
})
for i := 1; i <= 5; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 5.
}
Output: 0 1 1 2 2 3 3 3 5
Example (End) ¶
This example demonstrates how to end a Task. It creates a Task that prints the value of a State whenever it changes. The Task only prints 0, 1, 2 and 3 because it is ended after 3.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v)
if v < 3 {
return co.Await()
}
return co.End()
})
for i := 1; i <= 5; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 5.
}
Output: 0 1 2 3 5
Example (Memo) ¶
This example demonstrates how to use Memos to memoize cheap computations. Memos are evaluated lazily. They take effect only when they are acquired.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
s1, s2 := async.NewState(1), async.NewState(2)
sum := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() + s2.Get(); v != s.Get() {
s.Set(v) // Update s only when its value changes to stop unnecessary propagation.
}
})
product := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() * s2.Get(); v != s.Get() {
s.Set(v)
}
})
op := async.NewState('+')
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(op)
fmt.Println("op =", "'"+string(op.Get())+"'")
switch op.Get() {
case '+':
co.Spawn("sum", func(co *async.Coroutine) async.Result {
fmt.Println("s1 + s2 =", sum.Get())
return co.Await(sum)
})
case '*':
co.Spawn("product", func(co *async.Coroutine) async.Result {
fmt.Println("s1 * s2 =", product.Get())
return co.Await(product)
})
}
return co.Await()
})
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(3)
s2.Set(4)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
op.Set('*')
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(5)
s2.Set(6)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(7)
s2.Set(8)
op.Set('+')
}))
}
Output: op = '+' s1 + s2 = 3 --- SEPARATOR --- s1 + s2 = 7 --- SEPARATOR --- op = '*' s1 * s2 = 12 --- SEPARATOR --- s1 * s2 = 30 --- SEPARATOR --- op = '+' s1 + s2 = 15
Example (NonBlocking) ¶
This example demonstrates how to set up an autorun function to run an Executor in a goroutine automatically whenever a Coroutine is spawned or resumed.
package main
import (
"fmt"
"sync"
"github.com/b97tsk/async"
)
func main() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
s1, s2 := async.NewState(1), async.NewState(2)
sum := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() + s2.Get(); v != s.Get() {
s.Set(v)
}
})
product := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() * s2.Get(); v != s.Get() {
s.Set(v)
}
})
op := async.NewState('+')
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(op)
fmt.Println("op =", "'"+string(op.Get())+"'")
switch op.Get() {
case '+':
co.Spawn("sum", func(co *async.Coroutine) async.Result {
fmt.Println("s1 + s2 =", sum.Get())
return co.Await(sum)
})
case '*':
co.Spawn("product", func(co *async.Coroutine) async.Result {
fmt.Println("s1 * s2 =", product.Get())
return co.Await(product)
})
}
return co.Await()
})
wg.Wait() // Wait for autorun to complete.
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(3)
s2.Set(4)
}))
wg.Wait()
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
op.Set('*')
}))
wg.Wait()
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(5)
s2.Set(6)
}))
wg.Wait()
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(7)
s2.Set(8)
op.Set('+')
}))
wg.Wait()
}
Output: op = '+' s1 + s2 = 3 --- SEPARATOR --- s1 + s2 = 7 --- SEPARATOR --- op = '*' s1 * s2 = 12 --- SEPARATOR --- s1 * s2 = 30 --- SEPARATOR --- op = '+' s1 + s2 = 15
Example (Switch) ¶
This example demonstrates how a Coroutine can switch from one Task to another.
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v)
if v < 3 {
return co.Await()
}
return co.Switch(func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(switched)")
if v < 5 {
return co.Await()
}
return co.End()
})
})
for i := 1; i <= 7; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 7.
}
Output: 0 1 2 3 3 (switched) 4 (switched) 5 (switched) 7
Example (Yield) ¶
This example demonstrates how to yield a Coroutine only for it to resume later with another Task. It computes two values in separate goroutines sequentially, then prints their sum. It showcases what yielding can do, not that it's a useful pattern.
package main
import (
"fmt"
"sync"
"time"
"github.com/b97tsk/async"
)
func main() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
var myState struct {
async.Signal
v1, v2 int
}
myExecutor.Spawn("/", func(co *async.Coroutine) async.Result {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #1 here.
ans := 15
myExecutor.Spawn("/", async.Do(func() {
myState.v1 = ans
myState.Notify()
}))
}()
co.Watch(&myState)
// Yield preserves Events that are being watched.
return co.Yield(func(co *async.Coroutine) async.Result {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #2 here.
ans := 27
myExecutor.Spawn("/", async.Do(func() {
myState.v2 = ans
myState.Notify()
}))
}()
co.Watch(&myState)
return co.Yield(async.Do(func() {
fmt.Println("v1 + v2 =", myState.v1+myState.v2)
}))
})
})
wg.Wait()
}
Output: v1 + v2 = 42
Index ¶
- type Coroutine
- func (co *Coroutine) Await(s ...Event) Result
- func (co *Coroutine) Defer(f func())
- func (co *Coroutine) End() Result
- func (co *Coroutine) Executor() *Executor
- func (co *Coroutine) Path() string
- func (co *Coroutine) Spawn(p string, t Task)
- func (co *Coroutine) Switch(t Task) Result
- func (co *Coroutine) Watch(s ...Event)
- func (co *Coroutine) Yield(t Task) Result
- type Event
- type Executor
- type Memo
- type Result
- type Semaphore
- type Signal
- type State
- type Task
- type WaitGroup
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Coroutine ¶ added in v0.2.0
type Coroutine struct {
// contains filtered or unexported fields
}
A Coroutine is an execution of code, similar to a goroutine but cooperative and stackless.
A Coroutine is created with a function called Task. A Coroutine's job is to end the Task. When an Executor spawns a Coroutine with a Task, it runs the Coroutine by calling the Task function with the Coroutine as the argument. The return value determines whether to end the Coroutine or to yield it so that it could resume later.
In order for a Coroutine to resume, the Coroutine must watch at least one Event (e.g. Signal, State and Memo, etc.), when calling the Task function. A notification of such an Event resumes the Coroutine. When a Coroutine is resumed, the Executor runs the Coroutine again.
A Coroutine can also switch to work on another Task function according to the return value of the Task function. A Coroutine can switch from one Task to another until a Task ends it.
func (*Coroutine) Await ¶ added in v0.2.0
Await returns a Result that will cause co to yield. Await also accepts additional Events to be awaited for.
func (*Coroutine) Defer ¶ added in v0.2.0
func (co *Coroutine) Defer(f func())
Defer adds a function call when co resumes or ends, or when co is switching to work on another Task.
func (*Coroutine) End ¶ added in v0.2.0
End returns a Result that will cause co to end or switch to work on another Task in a Chain.
func (*Coroutine) Executor ¶ added in v0.2.0
Executor returns the Executor that spawned co.
Since co can be recycled by an Executor, it is recommended to save the return value in a variable first.
func (*Coroutine) Path ¶ added in v0.2.0
Path returns the path of co.
Since co can be recycled by an Executor, it is recommended to save the return value in a variable first.
func (*Coroutine) Spawn ¶ added in v0.2.0
Spawn creates an inner Coroutine to work on t, using the result of path.Join(co.Path(), p) as its path.
Inner Coroutines are ended automatically when the outer one resumes or ends, or when the outer one is switching to work on another Task.
func (*Coroutine) Switch ¶ added in v0.2.0
Switch returns a Result that will cause co to switch to work on t. co will be reset and t will be called immediately as the current Task of co.
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is the interface of any type that can be watched by a Coroutine.
The following types implement Event: Signal, State and Memo. Any type that embeds Signal also implements Event, e.g. State.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
An Executor is a Coroutine spawner, and a Coroutine runner.
When a Coroutine is spawned or resumed, it is added into an internal queue. The Run method then pops and runs each of them from the queue until the queue is emptied. It is done in a single-threaded manner. If one Coroutine blocks, no other Coroutines can run. The best practice is not to block.
The internal queue is a priority queue. Coroutines added in the queue are sorted by their paths. Coroutines with the same path are sorted by their arrival order (FIFO). Popping the queue removes the first Coroutine with the least path.
Manually calling the Run method is usually not desired. One would instead use the Autorun method to set up an autorun function to calling the Run method automatically whenever a Coroutine is spawned or resumed. The Executor never calls the autorun function twice at the same time.
func (*Executor) Autorun ¶
func (e *Executor) Autorun(f func())
Autorun sets up an autorun function to calling the Run method automatically whenever a Coroutine is spawned or resumed.
One must pass a function that calls the Run method.
If f blocks, the Spawn method may block too. The best practice is not to block.
func (*Executor) Run ¶
func (e *Executor) Run()
Run pops and runs every Coroutine in the queue until the queue is emptied.
Run must not be called twice at the same time.
type Memo ¶
type Memo[T any] struct { // contains filtered or unexported fields }
A Memo is a State-like structure that carries a value that can only be set in a Task-like function.
A Memo is designed to have a value that is computed from other States. What make a Memo useful are that:
- A Memo can prevent unnecessary computations when it isn't used;
- A Memo can prevent unnecessary propagations when its value isn't changed.
To create a Memo, use NewMemo or NewStrictMemo.
A Memo must not be shared by more than one Executor.
func NewMemo ¶
NewMemo returns a new non-strict Memo. The arguments are used to initialize an internal Coroutine.
One must pass a function that watches some States, computes a value from these States, and then updates the provided State if the value differs.
Like any Event, a Memo can be watched by multiple Coroutines. The watch list increases and decreases over time. For a non-strict Memo, when the last Coroutine in the list unwatches it, it does not immediately end its internal Coroutine. Ending the internal Coroutine would only put the Memo into a stale state because the Memo no longer detects dependency changes. By not immediately ending the internal Coroutine, a non-strict Memo prevents an extra computation when a new Coroutine watches it, provided that there are no dependency changes.
On the other hand, a strict Memo immediately ends its internal Coroutine whenever the last Coroutine in the watch list unwatches it. The Memo becomes stale. The next time a new Coroutine watches it, it has to make a fresh computation.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result is the type of the return value of a Task function. A Result determines what next for a Coroutine to do after calling a Task function.
A Result can be created by calling one of the following methods of Coroutine:
- Coroutine.End: for ending a Coroutine;
- Coroutine.Await: for yielding a Coroutine with additional Events to watch;
- Coroutine.Yield: for yielding a Coroutine with another Task to which will be switched later when resuming;
- Coroutine.Switch: for switching to another Task.
type Semaphore ¶ added in v0.2.0
type Semaphore struct {
// contains filtered or unexported fields
}
Semaphore provides a way to bound asynchronous access to a resource. The callers can request access with a given weight.
Note that this Semaphore type does not provide backpressure for spawning a lot of Tasks. One should instead look for a sync implemetation.
A Semaphore must not be shared by more than one Executor.
Example ¶
package main
import (
"fmt"
"sync"
"time"
"github.com/b97tsk/async"
)
func main() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
mySemaphore := async.NewSemaphore(10)
for n := int64(1); n <= 8; n++ {
myExecutor.Spawn("/", mySemaphore.Acquire(n).Then(async.Do(func() {
fmt.Println(n)
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(100 * time.Millisecond)
myExecutor.Spawn("/", async.Do(func() { mySemaphore.Release(n) }))
}()
})))
}
wg.Wait()
}
Output: 1 2 3 4 5 6 7 8
func NewSemaphore ¶ added in v0.2.0
NewSemaphore creates a new weighted semaphore with the given maximum combined weight.
type Signal ¶
type Signal struct {
// contains filtered or unexported fields
}
Signal is a type that implements Event.
Calling the Notify method of a Signal, in a Task function, resumes any Coroutine that is watching the Signal.
A Signal must not be shared by more than one Executor.
type State ¶
A State is a Signal that carries a value. To retrieve the value, call the Get method.
Calling the Set method of a State, in a Task function, updates the value and resumes any Coroutine that is watching the State.
A State must not be shared by more than one Executor.
type Task ¶
A Task is a piece of work that a Coroutine is given to do when it is spawned. The return value of a Task, a Result, determines what next for a Coroutine to do.
The argument co must not escape, because co can be recycled by an Executor when co ends.
func Chain ¶
Chain returns a Task that will work on each of the provided Tasks in sequence. When one Task ends, Chain works on another.
func Never ¶
func Never() Task
Never returns a Task that never ends. Tasks in a Chain after Never are never getting worked on.
func NoOperation ¶ added in v0.2.0
func NoOperation() Task
NoOperation returns a Task that ends without doing anything.
func (Task) Then ¶ added in v0.2.0
Then returns a Task that first works on t, then switches to work on next after t ends.
To chain multiple Tasks, use Chain function.
Example ¶
package main
import (
"fmt"
"github.com/b97tsk/async"
)
func main() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
a := func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(a)")
if v < 3 {
return co.Await()
}
return co.Switch(func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(switched)")
if v < 5 {
return co.Await()
}
return co.End()
})
}
b := func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(b)")
if v < 7 {
return co.Await()
}
return co.End()
}
myExecutor.Spawn("zz", async.Task(a).Then(b))
for i := 1; i <= 9; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 9.
}
Output: 0 (a) 1 (a) 2 (a) 3 (a) 3 (switched) 4 (switched) 5 (switched) 5 (b) 6 (b) 7 (b) 9
type WaitGroup ¶ added in v0.2.0
type WaitGroup struct {
Signal
// contains filtered or unexported fields
}
A WaitGroup is a Signal with a counter.
Calling the Add or Done method of a WaitGroup, in a Task function, updates the counter and, when the counter becomes zero, resumes any Coroutine that is watching the WaitGroup.
A WaitGroup must not be shared by more than one Executor.
Example ¶
package main
import (
"fmt"
"sync"
"time"
"github.com/b97tsk/async"
)
func main() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
var myState struct {
wg async.WaitGroup
v1, v2 int
}
myState.wg.Add(2) // Note that async.WaitGroup is not safe for concurrent use.
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #1 here.
ans := 15
myExecutor.Spawn("/", async.Do(func() {
myState.v1 = ans
myState.wg.Done()
}))
}()
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #2 here.
ans := 27
myExecutor.Spawn("/", async.Do(func() {
myState.v2 = ans
myState.wg.Done()
}))
}()
myExecutor.Spawn("/", myState.wg.Await().Then(async.Do(func() {
fmt.Println("v1 + v2 =", myState.v1+myState.v2)
})))
wg.Wait()
}
Output: v1 + v2 = 42
func (*WaitGroup) Add ¶ added in v0.2.0
Add adds delta, which may be negative, to the WaitGroup counter. If the WaitGroup counter becomes zero, Add resumes any Coroutine that is watching wg. If the WaitGroup counter is negative, Add panics.
func (*WaitGroup) Await ¶ added in v0.2.0
Await returns a Task that awaits until the WaitGroup counter becomes zero, and then ends.