线程锁

'''
 线程锁
 如果想保证共享数据的安全性,则需要添加Lock。(只要加锁则运算的速度就会变慢)
   步骤:
   from threading import Lock
   1. lock = Lock()  创建锁对象
   2. 获取锁:
      lock.acquire()  默认是阻塞,可以设置阻塞超时时间 timeout=秒

      释放锁:
      lock.release()
   总结: 哪段代码操作共享数据,则对其加锁
'''
import threading

number = 0


def task1():
    global number
    # 开始加锁
    lock.acquire()  # 获取
    for i in range(300000):
        number += 1
    # 释放锁
    lock.release()  # 释放
    print('{}的number值是:{}'.format(threading.current_thread().name, number))


def task2():
    global number
    # 开始加锁
    lock.acquire()  # 获取
    for i in range(300000):
        number += 1
    # 释放锁
    lock.release()  # 释放
    print('{}的number值是:{}'.format(threading.current_thread().name, number))


if __name__ == '__main__':
    lock = threading.Lock()

    t1 = threading.Thread(target=task1)
    t2 = threading.Thread(target=task2)

    t1.start()
    t2.start()

    t1.join()
    t2.join()
    print('最后获取number 的值是:', number)

import threading
from threading import Lock
from time import sleep


def task1():
    lock.acquire()
    print('{}拿到锁了...'.format(threading.current_thread().name))
    sleep(10)
    lock.release()
    print('{}释放锁了...'.format(threading.current_thread().name))


def task2():
    lock.acquire(timeout=5) # 线程2获取锁,如果锁被占用则当前线程就会阻塞等待
    print('{}拿到锁了...'.format(threading.current_thread().name))
    sleep(10)
    try:
        lock.release()
    except:
        print('没有拿到锁,是超时进入代码执行的...')
    else:
        print('{}释放锁了...'.format(threading.current_thread().name))


if __name__ == '__main__':
    lock = Lock()

    t1 = threading.Thread(target=task1)
    t2 = threading.Thread(target=task2)

    t1.start()
    t2.start()

 

发布了259 篇原创文章 · 获赞 6 · 访问量 4257
App 阅读领勋章
微信扫码 下载APP
阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览