我的测试代码如下,使用线程,count不是5,000,000,所以出现了data race,但是使用gevent,count是5,000,000,没有data race。
是不是gevent协程执行时会原子“count + = 1”,而不是拆分成一条CPU指令来执行?
# -*- coding: utf-8 -*-
import threading
use_gevent = True
use_debug = False
cycles_count = 100*10000
if use_gevent:
from gevent import monkey
monkey.patch_thread()
count = 0
class Counter(threading.Thread):
def __init__(self, name):
self.thread_name = name
super(Counter, self).__init__(name=name)
def run(self):
global count
for i in xrange(cycles_count):
if use_debug:
print '%s:%s' % (self.thread_name, count)
count = count + 1
counters = [Counter('thread:%s' % i) for i in range(5)]
for counter in counters:
counter.start()
for counter in counters:
counter.join()
print 'count=%s' % count