Skip to content

Instantly share code, notes, and snippets.

@Fawers
Created April 11, 2019 23:04
Show Gist options
  • Save Fawers/ce452db925f3e0bdb25d03e4f0ab20da to your computer and use it in GitHub Desktop.
Save Fawers/ce452db925f3e0bdb25d03e4f0ab20da to your computer and use it in GitHub Desktop.
async - go and python
// https://repl.it/@fswerneck/goroutines
package main
import "fmt"
func consume(q <-chan interface{}, finish chan<- bool) {
fmt.Println("getting from q")
mydata := <-q
fmt.Printf("got %v from q\n", mydata)
finish <- true
}
func main() {
q := make(chan interface{}, 2)
finish := make(chan bool)
tasks := 5
fmt.Println("q created")
fmt.Println("scheduling 10 goroutines")
for i := 0; i < tasks; i++ {
go consume(q, finish)
}
q <- 1
fmt.Println("put 1")
q <- 2
fmt.Println("put 2")
q <- 3
fmt.Println("put 3")
q <- 4
fmt.Println("put 4")
q <- 5
fmt.Println("put 5")
for i := 0; i < tasks; i++ {
<-finish
}
fmt.Println("finished")
}
# https://repl.it/@fswerneck/coroutines
import asyncio
async def consume(q: asyncio.Queue):
print("getting from q")
mydata = await q.get()
print(f"got {mydata} from q")
q.task_done()
async def main():
q = asyncio.Queue(2)
tasks = 5
print("q created")
print("scheduling 10 coroutines")
for i in range(tasks):
asyncio.ensure_future(consume(q))
await q.put(1)
print("put 1")
await q.put(2)
print("put 2")
await q.put(3)
print("put 3")
await q.put(4)
print("put 4")
await q.put(5)
print("put 5")
await q.join()
print("finished")
# The piece below is completely abstracted by Go;
# everything in Go runs in an event loop.
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

go:

$ go run main.go 
q created
scheduling 10 goroutines
put 1
put 2
getting from q
got 1 from q
put 3
getting from q
got 2 from q
put 4
getting from q
got 3 from q
put 5
getting from q
got 4 from q
getting from q
got 5 from q
finished

python:

$ python3 main.py 
q created
scheduling 10 coroutines
put 1
put 2
getting from q
got 1 from q
getting from q
got 2 from q
getting from q
getting from q
getting from q
put 3
put 4
got 3 from q
got 4 from q
put 5
got 5 from q
finished
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment