• python_多线程加锁


    python3多线程可以不加锁,每个多线程就自带锁

    python2多线程必须加锁,多线程本身不带锁

    加锁有两种方式,一种如下图: 

    import time, threading
    count=0 #声明全局变量
    lock=threading.Lock() #申请一把锁
    def lajifenlei():
        global count #引用全局变量
        lock.acquire()  #加锁
        count+=1
        lock.release() #释放锁
        time.sleep(1)
        print(count)
    
    for i in range(10):
        th = threading.Thread(target=lajifenlei,) #声明线程数
        th.start() #启动线程
    while threading.activeCount()!=1:
        pass
    
    C:UserszhaowAppDataLocalProgramsPythonPython37python.exe D:/study/python/atp/lib/t.py
    10
    1010
    101010
    10
    
    10
    
    1010

    另一种类似打开和关闭文件的with方法,自动开关锁

    import time, threading
    count=0 #声明全局变量
    lock=threading.Lock() #申请一把锁
    def lajifenlei():
        global count #引用全局变量
    
        with lock: #with模块自动加锁及解锁
         count+=1
    
        time.sleep(1)
        print(count)
    
    for i in range(10):
        th = threading.Thread(target=lajifenlei,) #声明线程数
        th.start() #启动线程
    while threading.activeCount()!=1:
        pass
  • 相关阅读:
    判断一下是星期几
    猴子分桃
    免子生免子
    字符串排序
    非关系型数据库(一)
    学习redis简介(一)
    SAVEPOINT
    *****POSTGRESQL文檔
    程序员人生之路(分析的非常透彻!)
    UpperCase for ALL Text Editors
  • 原文地址:https://www.cnblogs.com/xiaokuangnvhai/p/11271878.html
Copyright © 2020-2023  润新知