小编onl*_*cai的帖子

为什么使用线程会发生数据竞争,而不会使用gevent

我的测试代码如下,使用线程,count不是5,000,000,所以出现了数据竞争,但是使用gevent,count是5,000,000,没有数据竞争。

是不是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' % …
Run Code Online (Sandbox Code Playgroud)

python gevent

5
推荐指数
1
解决办法
697
查看次数

标签 统计

gevent ×1

python ×1