Why use threading data race will occur, but will not use gevent

Posted by onlytiancai on Stack Overflow See other posts from Stack Overflow or by onlytiancai
Published on 2013-10-29T03:17:16Z Indexed on 2013/10/29 3:54 UTC
Read the original article Hit count: 156

Filed under:
|

My test code is as follows, using threading, count is not 5,000,000 , so there has been data race, but using gevent, count is 5,000,000, there was no data race .

Is not gevent coroutine execution will atom "count + = 1", rather than split into a one CPU instruction to execute?

# -*- 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

© Stack Overflow or respective owner

Related posts about python

Related posts about gevent