forked from status-im/nim-chronos
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
status-im#542 Add first draft for chronos-multithreading docs
- Loading branch information
=
committed
May 21, 2024
1 parent
8a30676
commit 65f0080
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import std/[os] | ||
import chronos | ||
import chronos/threadsync | ||
|
||
proc cleanupThread*() {.gcsafe, raises: [].}= | ||
{.cast(gcsafe).}: | ||
try: | ||
`=destroy`(getThreadDispatcher()) | ||
when defined(gcOrc): | ||
GC_fullCollect() | ||
except Exception as e: | ||
echo "Exception during cleanup: ", e[] | ||
|
||
proc processAsync() {.async.} = | ||
await sleepAsync(1000) # Waiting on an HTTP Request or the like | ||
echo "Done with async work" | ||
|
||
proc threadProc(threadSignal: ThreadSignalPtr) {.thread.} = | ||
block: | ||
asyncSpawn processAsync() # Start some async work | ||
|
||
waitFor threadSignal.wait() # Do async work and then go to sleep until main thread wakes you up | ||
|
||
cleanupThread() # Clean up thread local variables, e.g. dispatcher | ||
|
||
var thread: Thread[ThreadSignalPtr] | ||
let signal = new(ThreadSignalPtr)[] | ||
|
||
createThread(thread, threadProc, signal) | ||
sleep(10) | ||
discard signal.fireSync() | ||
|
||
joinThread(thread) | ||
discard signal.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Multithreading with async event-loops | ||
|
||
At times you may want to run asynchronous work on another thread for whatever reason, | ||
then wait while working through the asynchronous work until you receive a signal to continue. | ||
|
||
This kind of setup can be facilitated by using `threadSync/ThreadSignalPtr` | ||
|
||
```nim | ||
{{#include ../examples/multithreading.nim}} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters