src/threadButler

Source   Edit  

This package provides a way to set-up multithreading with multiple long-running threads that talk to one another via message passing.

The architecture is modeled after a client-server architecture between threads, with one thread running the GUI loop and one or more other threads acting running their own event-loops, listening for messages and acting as backend "servers".

Threadbutler groups message-types and handler procs defining what to do with a given message-type into a single thread. It then defines one overarching message-variant that encompasses all messages that are allowed to be sent to that thread.

For integration utilities with other frameworks see:

Types

KillError = object of CatchableError
A custom error. Throwing this will gracefully shut down the server Source   Edit  

Vars

IS_RUNNING: Atomic[bool]
Global switch that controls whether threadServers keep running or shut down. Change this value to false to trigger shut down of all threads running ThreadButler default event-loops. Source   Edit  

Procs

proc clearServerChannel[Msg](data: Server[Msg])
Convenience proc for clearServerChannel Source   Edit  
proc clearServerChannel[Msg](hub: ChannelHub; t: typedesc[Msg])
Throws away remaining messages in the channel. This avoids those messages leaking should the channel be destroyed. Source   Edit  
proc clearThreadVariables() {....raises: [], tags: [], forbids: [].}
Internally, this clears up known thread variables that were likely set to avoid memory leaks. May become unnecessary if https://github.com/nim-lang/Nim/issues/23165 ever gets fixed Source   Edit  
proc keepRunning(): bool {....raises: [], tags: [], forbids: [].}
Source   Edit  
proc run[Msg](thread: var Thread[Server[Msg]]; data: Server[Msg])
Source   Edit  
proc send[Msg](server: Server[Msg]; msg: auto): bool
Utility proc to allow sending messages directly from a server object. Source   Edit  
proc serverProc[Msg](data: Server[Msg]) {....gcsafe.}
Source   Edit  
proc shutdownAllServers() {....raises: [], tags: [], forbids: [].}
Source   Edit  
proc shutdownServer() {....raises: [KillError], tags: [], forbids: [].}
Triggers the graceful shut down of the thread-server this proc is called on. Source   Edit  

Templates

template withServer(hub: ChannelHub; threadName: static string; body: untyped)

Spawns the server on the thread associated with threadName.

The server listens for new messages and executes routeMessage for every message received, which will call the registered handler proc for this message type. startup and shutdown events in data are executed before and after the event-loop of the server.

Sends message to shut the server down gracefully and waits for shutdown to complete once the code in body has finished executing.

Source   Edit