文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>转载:原子级别操作

转载:原子级别操作

时间:2010-03-30  来源:broader

http://29a.ch/2009/2/20/atomic-get-and-increment-in-python

Atomic get and increment in python

written by Jonas Wagner, on 2/21/09 12:19 AM.

For generating continuous unique id's in python I needed a thread safe way to do this:
x = counter
counter += 1
When disassembling this code we will get this:
  2           0 LOAD_FAST                0 (counter)
3 STORE_FAST 1 (x)

3 6 LOAD_FAST 0 (counter)
9 LOAD_CONST 1 (1)
12 INPLACE_ADD
13 STORE_FAST 0 (counter)
As you can see not even counter += 1 is atomic. Now the obvious solution would be to use a lock. The not so obvious solution is to use a itertools.counter(). The counter is implemented in C and doesn't release the GIL so it is atomic. The code would the look like this:
x = counter.next()
which is more pretty anyway.
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载