问下,为什么这个程序执行到最后,打印了很多Thread-5,是线程5重复执行了?
如果我把sub中的time.sleep(1)注释的话,就是一个线程一个线程执行程序!
麻烦解答!
import threading, time
num = 5
lock = threading.Lock() # 创建同步锁
L = []
def sub():
global num
print('sub %s' % t.name)
lock.acquire() # 获得同步锁:不让别的线程在同一时刻运行
print(t.name)
temp = num
time.sleep(1)
num = temp - 1
lock.release() #解除同步锁
print('%s ' % t.name, num)
for i in range(5):
t = threading.Thread(target=sub)
t.start()
print('start %s' % t.name)
# L.append(t)
for T in L:
T.join()
print('s', num)
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
for 循环循环了5次之后,t 就是线程5了呀.
这个里面的t 是全局的,for循环五次后,正好是线程5.然后你打印肯定是线程5 呀
下面是正确写法:
for循环print语句确定在循环外面?