

事实上每次运行结果都不相同且不正确,这证明单核CPU+PIL仍无法保证线程安全,需要加锁.
加锁后的正确代码:
# -*- coding: utf-8 -*-
import threading
import time
count = 0
lock = threading.Lock()
class Counter(threading.Thread):
def __init__(self, name):
self.thread_name = name
self.lock = threading.Lock()
super(Counter, self).__init__(name=name)
def run(self):
global count
global lock
for i in xrange(100000):
lock.acquire()
count = count + 1
lock.release()
counters = [Counter('thread:%s' % i) for i in range(5)]
for counter in counters:
counter.start()
time.sleep(5)
print 'count=%s' % count结果:
count=500000
注意锁的全局性
这是一个简单的Python语法问题,但在逻辑复杂时有可能被忽略.
要保证锁对于多个子线程来说是共用的,即不要在Thread的子类内部创建锁.
以下为错误代码
# -*- coding: utf-8 -*-
import threading
import time
count = 0
# lock = threading.Lock() # 正确的声明位置
class Counter(threading.Thread):
def __init__(self, name):
self.thread_name = name
self.lock = threading.Lock() # 错误的声明位置
super(Counter, self).__init__(name=name)
def run(self):
global count
for i in xrange(100000):
self.lock.acquire()
count = count + 1
self.lock.release()
counters = [Counter('thread:%s' % i) for i in range(5)]
for counter in counters:
print counter.thread_name
counter.start()
time.sleep(5)
print 'count=%s' % count