python – gevent,套接字和同步

我在一个公共套接字上发送了多个greenlet.是否保证通过socket.sendall发送的每个包都是完全分离的,或者我必须在每次调用sendall之前获取一个锁.

所以我想阻止以下情况:

> g1发送ABCD
> g2发送1234
>收到的数据混淆了,例如AB1234CD
>预计是ABCD1234或1234ABCD

更新

看了sourcecode后我认为这种情况不可能发生.但我必须使用锁,因为g1或g2可能会在sendall上崩溃.有人能证实吗?

最佳答案 我做了一些带有高延迟/低带开关接口的测试,并得到了预期的错误.

>慢速接口仿真:https://superuser.com/a/147434
>测试脚本:https://gist.github.com/4249827/6779dfbebc255e81252e9b29c94add98c5771669

这导致(如预期)出现以下错误:

AssertionError: This event is already used by another greenlet: (<Greenlet 
at 0x7f3e758722d0: <bound method socket.sendall of <socket at 0x7f3e7587719
0 fileno=8 sock=127.0.0.1:1234 peer=127.0.0.1:51042>>('11111111111111111111
11111111111111111111111111111)>, timeout('timed out',))

这是带有gevent.coros.RLock的固定测试脚本,它不会产生此错误:https://gist.github.com/4249827/7f02f805331eda4091ae0b39dfea4b102cdba2fa

点赞