来源:Python threading中lock的使用_锅炉房刘大爷的博客-优快云博客
threading.lock()
先给出代码例子:
import threading
import time
lock = threading.Lock()
l = []
def test1(n):
lock.acquire()
l.append(n)
print l
lock.release()
def test(n):
l.append(n)
print l
def main():
for i in xrange(0, 10):
th = threading.Thread(target=test, args=(i, ))
th.start()
if __name__ == '__main__':
main()
当有很多个线程一起输出的时候,如果不设置锁lock的话,输出的时候会很乱,像下面一样:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3][
0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4[, 05, , 16, , 27, ]3
, 4, 5, 6[, 07, , 18, ]2
, 3, 4, [50, , 61, , 72, , 83, , 94],
5, 6, 7, 8, 9]
但是换了有lock之后输出就会有顺序:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
就是等上一个进程完成之后才开始下个进程进行。