1. 程式人生 > >python 執行緒互斥鎖用法 簡單案例 threading.Lock()

python 執行緒互斥鎖用法 簡單案例 threading.Lock()

# encoding: UTF-8
import threading
import time

# # 建立鎖
# lock=threading.Lock()
# # 鎖定
# lock.acquire()
# # 釋放
# lock.release()


def test_xc(num):
    f = open("test.txt", "a")
    f.write(str(num) + '\n')
    time.sleep(1)
    lock.acquire()  # 取得鎖
    f.close()
    lock.release()  # 釋放鎖


if __name__ == '__main__':
    lock = threading.Lock()  # 建立鎖
    for i in xrange(5):
        t = threading.Thread(target=test_xc,args=('abc',))
        t.start()
環境python2.7