风-fmgao

导航

线程互斥锁

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/18
from threading import Thread, Lock
import time

n = 100


def task():
    global n
    mutex.acquire()  # 阻止其他99个线程在这里等待,保证数据安全
    temp = n
    time.sleep(0.1)  # 启动一个线程,睡0.1秒足够100个线程全部启动
    n = temp - 1  # 100个线程全部修改为99
    mutex.release()


if __name__ == '__main__':
    mutex = Lock()
    t_l = []
    time1 = time.time()
    for i in range(100):  # 一个进程内开了100个线程
        t = Thread(target=task)
        t_l.append(t)
        t.start()

    for i in t_l:
        t.join()  # 保证主线程执行完毕
    time2 = time.time()
    time3 = time2-time1
    print('主', n, time3)  # 主 0 10.06277322769165


posted on 2018-06-18 10:29  风-fmgao  阅读(114)  评论(0编辑  收藏  举报