Skip to content

Can Weave spawn a thread that sends a Channel message to the main channel without blocking the main thread? #198

Description

@PhilippMDoerner

Heyho, I am trying to get an example to work where I spawn a thread to perform a task in weave that eventually sends a Channel message, while the proc itself returns nothing.

I want to go for a Channel message as I want a setup with a thread running an event-loop of a GUI that regularly reads messages send to it from possibly multiple other "Task"-threads.

It should not ever block waiting for any of the "Task"-threads to finish as it should run its own event-loop and stay responsive to user-input.

The code would look roughly like this (if spawn only spawned a single thread for that one proc call):

import weave
import std/os

var chan: Channel[string]
chan.open()

proc doThing() {.gcsafe.} =
  sleep(1000) # Very compute intensive task or one where you waitFor an async operation like an HTTP request
  chan.send("Sending")

proc guiLoop() =
  var counter: int

  while true: # A GUI loop
    let resp = chan.tryRecv
    counter.inc
    if resp.dataAvailable:
      echo resp.msg
      echo "Counter: ", counter
      break
    
    sleep(10)

proc main() =
  init(Weave)
  
  spawn doThing()

  guiLoop()
    
  exit(Weave)

main()

Now obviously the above does not work.
I'm not entirely sure what it does, but I'm very sure it spawns more than 1 thread as it maxes out my 16 core CPU on top of never even starting to execute doThing.

Is there a way to express that with weave?

I initially assumed that this fell under "task parallelism" since I would want to do 2 tasks in parallel (run gui thread, execute "doThing"), but I'm really not that knowledgeable with the terminology thrown around.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions