python自动化web测试-线程锁


import threading

lock = threading.Lock()  # 创建Lock对象
def lock_test():
    global lock  # 声明为全局变量,每个线程函数中都要声明
    for i in range(10):
        lock.acquire()  # 上锁,之后的同步代码,只能一个线程访问
        id = threading.currentThread().ident #获取当前线程的ID
        print("id:%d"%id)
        lock.release()  # 解锁

def main():
    #创建线程
    th1 = threading.Thread(target=lock_test)
    th2 = threading.Thread(target=lock_test)
    th3 = threading.Thread(target=lock_test)

    th1.start()
    th2.start()
    th3.start()

    th1.join()
    th2.join()
    th3.join()

if __name__=='__main__':
   main()

运行结果:

id:26920
id:26920
id:26920
id:26920
id:26920
id:26920
id:26920
id:26920
id:26920
id:26920
id:21700
id:21700
id:21700
id:21700
id:21700
id:21700
id:21700
id:21700
id:21700
id:21700
id:21188
id:21188
id:21188
id:21188
id:21188
id:21188
id:21188
id:21188
id:21188
id:21188

猜你喜欢

转载自blog.csdn.net/qq_40904479/article/details/105690037