rgalanakis/goless

Question about goless

Closed this issue · 3 comments

I'm trying out goless, but I'm not sure if it's working for me as intended. I expect to get interleaved output from this program:

import goless
import time

def one():
    while True:
        time.sleep(1)
        print('one')

def two():
    while True:
        time.sleep(1)
        print('two')

goless.go(one)
goless.go(two)
print('Launched both')
goless.chan().recv()

But I get this output:

Launched both
one
one
one
one
one
one
one
one
one
one
one
^C

Is this expected, or something wrong with the way I'm using goless?

Yes, you're using goless/asynchrony wrong :) You can see an example of something similar to your example here: https://github.com/rgalanakis/goless/blob/master/tests/test_examples.py#L14
There are a few things, both technical and conceptual:

  • First, using time.sleep just pauses the current thread. It does not do any switching between coroutines. You would have to use gevent.sleep or a similar mechanism for Stackless (or goless.backend.yield).
  • You are creating and receiving on a channel but never sending to it.
  • So what's happening is: 1) Create a couple coroutines via goless.go, 2) recv on a channel and switch to the next coroutine, 3) loop and sleep forever.

Asynchronous programming using coroutines and channels is not like synchronous programming, but once you get the hang of it is really awesome. Please study the examples and docs included in goless; you can also look at Stackless Python's help for more examples (gevent doesn't stress the same pattern of asynchronous programming so its docs are less helpful here).

Does that help?

Thanks for the explanation. I'm not familiar at all with Stackless. I guess I was expecting the behavior we'd get from a similar program in Go (suppose in the Python example time.sleep was replaced with something that just takes a long time). But that's probably what the docs are saying in the goless and the GIL section?

Well, not exactly.
The main thread just recvs on a channel, waiting for a message to be sent. The goroutine never sends anything on the channel, so the channel continues to recv.
I'm still unclear what behavior you are expecting. Can you explain how you expect your program to work and why?