Thursday 21 March 2013

Eventlet snippets

OpenStack services use the green threads model as described here. I found an excellent explanation of Eventlet in a video by Donovan Preston. I have typed in some of the snippets he uses here.




Spawning a green thread


$ python spawn.py
<eventlet.greenthread.GreenThread object at 0xe77870>
1 + 2 = 3

Cooperative yielding


$ python co-op.py 
func2
func1

$ python interleave.py 
main:   i=0
foo(A): i=0
foo(B): i=0
main:   i=1
foo(A): i=1
foo(B): i=1
main:   i=2
foo(A): i=2
foo(B): i=2


Not so cooperative



$ python un-co-op.py 
main: i=0
main: i=1
main: i=2
foo(A): i=0
foo(A): i=1
foo(A): i=2
foo(B): i=0
foo(B): i=1
foo(B): i=2

Synchronization queue


$ python queue.py 
func1 hello
func2 world

Sychronization event


$ python waiter.py
sending
sent
waiter

$ python waiter2.py
main: before send()
waiter: before wait()
main: after send()
waiter: after wait()
main: at end


Green pools


$ python greenpool.py 
execute 1
execute 2
execute 3
1
2
execute 4
3
4

Green sockets


Start the echo server:
$ python greensocket.py
server listening on port 6000

then start another terminal and any lines typed are echoed: 
$ nc localhost 6000
something from client1
something from client1

Now the point is that the program is not blocked handling that socket. So start another terminal:
$ nc localhost 6000
something from client2
something from client2

Then press control-d in each nc to disconnect. The entire server output is:
$ python greensocket.py 
server listening on port 6000
client connected
echoed something from client1
client connected
echoed something from client2
disconnected
disconnected