这几天我尝试使用猴子补丁。我发现,如果代码是猴子修补,它将产生不同的thread.ident。这是否意味着猴子补丁启动了多个线程,而不是多个协同程序?
如果它启动了多个线程,那么就会带来竞争条件,不是吗?
请帮助,提前谢谢。
我使用了两个测试代码。
没有monkey_patch(),阻止代码,但打印相同的线程ID。
#!/usr/bin/env python
# encoding: utf-8
import eventlet
# comment monkey_patch
# eventlet.monkey_patch()
import time
import thread
workers=4
jobs = 5
record = {}
pool = eventlet.greenpool.GreenPool()
def do_work(index):
global record
record[index] = record.get(index, 0) + 1
# data = "worker=%s: %s \n" % (index, record[index])
# print data
# eventlet.greenthread.sleep(1)
# block
time.sleep(1)
def work(worker, jobs):
for x in xrange(0, jobs):
# print same thread id
print "worker in thread %s" % thread.get_ident()
do_work(worker)
for i in xrange(workers):
print 'worker: %s do %s jobs'% (i, jobs)
pool.spawn(work, i, jobs)
pool.waitall()
输出如下:
[root@172-18-211-195 shengping]# python test_mky.py
worker: 0 do 5 jobs
worker: 1 do 5 jobs
worker: 2 do 5 jobs
worker: 3 do 5 jobs
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
worker in thread 140221126620992
使用monkey_patch(),解锁代码,但打印不同的主题ID。
#!/usr/bin/env python
# encoding: utf-8
import eventlet
# comment monkey_patch
eventlet.monkey_patch()
import time
import thread
workers=4
jobs = 5
record = {}
pool = eventlet.greenpool.GreenPool()
def do_work(index):
global record
record[index] = record.get(index, 0) + 1
# data = "worker=%s: %s \n" % (index, record[index])
# print data
# eventlet.greenthread.sleep(1)
# block
time.sleep(1)
def work(worker, jobs):
for x in xrange(0, jobs):
# print same thread id
print "worker in thread %s" % thread.get_ident()
do_work(worker)
for i in xrange(workers):
print 'worker: %s do %s jobs'% (i, jobs)
pool.spawn(work, i, jobs)
pool.waitall()
输出如下(因为你可以看到每个具有不同线程ID的工人):
[root@172-18-211-195 shengping]# python test_mky.py
worker: 0 do 5 jobs
worker: 1 do 5 jobs
worker: 2 do 5 jobs
worker: 3 do 5 jobs
worker in thread 27456048
worker in thread 27456208
worker in thread 27456368
worker in thread 27456528
worker in thread 27456048
worker in thread 27456208
worker in thread 27456368
worker in thread 27456528
worker in thread 27456048
worker in thread 27456208
worker in thread 27456368
worker in thread 27456528
worker in thread 27456048
worker in thread 27456208
worker in thread 27456368
worker in thread 27456528
worker in thread 27456048
worker in thread 27456208
worker in thread 27456368
worker in thread 27456528
答案 0 :(得分:0)
tpool