如何在龙卷风中实现协程锁

时间:2012-08-31 04:38:01

标签: python asynchronous synchronization coroutine

我理解龙卷风中的corountine的机制,但这是我无法弄清楚的问题,请帮我一把

考虑这个业务例程:这里有5个数据库操作

#operation 1
#use asynchronous method ,doesn't matter
#switch to other coroutine

#operation 2
#use asynchronous method ,doesn't matter
#switch to other coroutine


#operation 3
#use asynchronous method , but i'll use the result do 
#some process then update in operation 4
#switch to other coroutine


#operation 4
#use asynchronous method ,doesn't matter
#switch to other coroutine


#operation 5
#use asynchronous method ,doesn't matter
#switch to other coroutine

正如你所看到的,我不希望任何其他相关的协程更新到同一个表或每个操作3和操作4之间的相同记录,它会使脏读和写。换句话说

#coroutine 1 operation 3
#coroutine 2 operation 3
#coroutine 1 operation 4
#coroutine 2 operation 4

不会被接受,正确的顺序应该是

#coroutine 1 operation 3
#coroutine 1 operation 4
#coroutine 2 operation 3
#coroutine 2 operation 4

我可以在操作3使用块方法,但是这会阻塞整个服务器,我希望主循环不会执行某些协同程序,直到我告诉他们释放。

1 个答案:

答案 0 :(得分:0)

在我考虑之后,这是愚蠢的。

这在单线程程序实践中非常简单和基本

global flag
while flag:
    do some asynchronous empty callback
flag = True

#operation 3
#use asynchronous method , but i'll use the result do 
#some process then update in operation 4
#switch to other coroutine

#operation 4
#use asynchronous method ,doesn't matter
#switch to other coroutine

flag = False

完成。