其实可以不需要使用lock
Topic sourcelock只是锁住了修改参数的过程而已,你这里确实是直接把程序变成串行的了。 你这样做,对于这个问题确实可以实现相同的操作,因为他确实只有一个步骤(甚至不算for...range 那里)。但是在别的地方就不能这么用了。一个线程可以有很多步骤的,lock只是锁了其中一个步骤而已。
它只是保持每次只有一个线程操作参数,但是不代表每个线程的操作是顺序的,下面这程序多运行几次会发现它并不是线性运行的,它是由系统分配运行的
import threading
import time, random
class myThread (threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print ("开启线程: " + self.name)
#获取锁,用于线程同步
threadLock.acquire()
print_time(self.name, 4)
# 释放锁,开启下一个线程
threadLock.release()
def print_time(threadName, counter):
while counter:
time.sleep(0.4)
#打印时间
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
th_name = ["Thread-1","Thread-2","Thread-3","Thread-4"]
# 创建新线程
for i, n in zip(range(1,5),th_name):
t = myThread(i, n)
t.start()
threads.append(t)
#t.join()
# 开启新线程
for t in threads:
t.join()
~
执行结果:
开启线程: Thread-1
开启线程: Thread-2
开启线程: Thread-4
开启线程: Thread-3
Thread-1: Sat May 12 01:38:57 2018
Thread-1: Sat May 12 01:38:57 2018
Thread-1: Sat May 12 01:38:58 2018
Thread-1: Sat May 12 01:38:58 2018
Thread-2: Sat May 12 01:38:59 2018
Thread-2: Sat May 12 01:38:59 2018
Thread-2: Sat May 12 01:38:59 2018
Thread-2: Sat May 12 01:39:00 2018
Thread-4: Sat May 12 01:39:00 2018
Thread-4: Sat May 12 01:39:01 2018
Thread-4: Sat May 12 01:39:01 2018
Thread-4: Sat May 12 01:39:01 2018
Thread-3: Sat May 12 01:39:02 2018
Thread-3: Sat May 12 01:39:02 2018
Thread-3: Sat May 12 01:39:03 2018
Thread-3: Sat May 12 01:39:03 2018
- 1
梦想家高先森
把例子中的
修改为
如此,便可以不需要使用低级的
lock()
,也能得到正确的结果。