>>> import threading >>> a = 0 >>> defadd1(): ... global a ... a += 1 ... print('%s adds a to 1: %d'%(threading.current_thread().getName(), a)) ... >>> threads = [threading.Thread(name='t%d'%(i,), target=add1) for i inrange(10)] >>> [t.start() for t in threads]
执行结果
1 2 3 4 5 6 7 8 9 10 11
t0 adds a to 1: 1 t1 adds a to 1: 2 t2 adds a to 1: 3 t3 adds a to 1: 4 t4 adds a to 1: 5 t5 adds a to 1: 6 t6 adds a to 1: 7 t7 adds a to 1: 8 t8 adds a to 1: 9 t9 adds a to 1: 10 [None, None, None, None, None, None, None, None, None, None]
>>> import threading >>> import time >>> a = 0 >>> defadd1(): ... global a ... tmp = a+1 ... time.sleep(0.2) # 延迟0.2秒,模拟写入所需要时间 ... a = tmp ... print('%s adds a to 1:%d'%(threading.current_thread().getName(),a)) ... >>> threads = [threading.Thread(name='t%d'%(i,), target=add1) for i inrange(10)] >>> [t.start() for t in threads] [None, None, None, None, None, None, None, None, None, None]
运行代码,仅仅一次,问题就很快完全暴露,结果如下:
1 2 3 4 5 6 7 8 9 10
>>> t0 adds a to 1:1 t1 adds a to 1:1 t2 adds a to 1:1 t3 adds a to 1:1 t4 adds a to 1:1 t5 adds a to 1:1 t7 adds a to 1:1 t6 adds a to 1:1 t8 adds a to 1:1 t9 adds a to 1:1
# 2. 获得锁和释放锁 defadd1(): global a try: locka.acquire() # 获得锁 tmp = a + 1 time.sleep(0.2) # 演示0.2秒。模拟写入所需时间 a = tmp finally: locka.release() # 释放锁 print('%s adds a to 1:%d' % (threading.currentThread().getName(), a))
# 3.创建和开始线程 threads = [threading.Thread(name='t%d' % (i,), target=add1) for i inrange(10)] [t.start() for t in threads]
执行结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
/Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/thread_sample_01.py t0 adds a to 1:1 t1 adds a to 1:2 t2 adds a to 1:3 t3 adds a to 1:4 t4 adds a to 1:5 t5 adds a to 1:6 t6 adds a to 1:7 t7 adds a to 1:8 t8 adds a to 1:9 t9 adds a to 1:10
defA(): a_list = ['1', '2', '3'] for to_b in a_list: from_b = yield to_b print('receive %s from B' % (from_b,)) print('do some complex process for A during 200ms')
defB(a): from_a = a.send(None) print('response %s from A' % (from_a)) print('B is analysising data from A') b_list = ['x', 'y', 'z'] try: for to_a in b_list: from_a = a.send(to_a) print('receive %s from B' % (from_a,)) print('B is analysising data from A') except StopIteration: print('----from a done----') finally: a.close()
# 调用 a = A() B(a)
执行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/thread_sample_02.py response 1from A B is analysising data from A receive x from B do some complex process for A during 200ms receive 2from B B is analysising data from A receive y from B do some complex process for A during 200ms receive 3from B B is analysising data from A receive z from B do some complex process for A during 200ms ----from a done----