> But I dont realy want to create a new thread every time. So is there a better 
> way of achieving this? (it may be linux specific)

Make the proc is always running the background as a dedicated thread but lock 
it to save the cpu loop and only continue if the lock receiving signal.

For example here:
    
    
    import std/[locks, strformat, times, threadpool, os]
    
    var
      chan: Channel[string]
      cond: Cond
      lock: Lock
    let startTime = now()
    
    initLock lock
    initCond cond
    chan.open
    
    proc bgExec {.thread.} =
        while true:
            let data = tryRecv chan
            if data.dataAvailable:
                if data.msg == "": break
                echo fmt"'{data.msg}' at duration {now() - startTime} from 
{startTime}"
                continue
            
            cond.wait lock
    
    template runit(msg: string) =
        chan.send msg
        cond.signal
    
    proc main {.thread.} =
        runit "start"
        sleep 200
        runit "after 200 ms"
        sleep 100
        runit "after 300 ms"
        sleep 200
        runit "after 500 ms"
        runit "stop"
        runit ""
    
    spawn bgExec()
    spawn main()
    sync()
    
    
    Run

In this example, channel is used to illustrate the stream of "what you want to 
execute" but it can be anything. The key part is the `continue`, 
`condition.wait(lock)` and `condition.signal()`

  * `continue` is needed to immediately check whether there's another message 
before waiting on lock
  * waiting for lock is to avoid wasted cpu loop
  * signal is to tell the condition it's ok stop waiting.



[Run it on playground](https://play.nim-lang.org/#ix=4EfX)

Reply via email to