zoukankan      html  css  js  c++  java
  • Python 多线程编程

    import threading
    import time
    g_nums = [11, 22]
    g_num = 0
    # 创建一个互斥锁,默认是没有上锁的
    mutex = threading.Lock()
    
    
    def test1():
        for i in range(5):
            print("test1------%d------" % i)
            time.sleep(1)
    
    
    def test2():
        for i in range(5):
            print("test2------%d------" % i)
            time.sleep(1)
    
    
    def test3(temp):
        temp.append(33)
        print(temp)
    
    
    def test4():
        global g_num
        # 上锁,如果之前没有被上锁,那么此时 上锁成功
        # 如果上锁之前 已经被上锁了,那么此时会堵塞在这里,直到 这个锁被解开为止
        mutex.acquire()
        for i in range(1000000):
            g_num += 1
        # 解锁
        mutex.release()
        print(g_num)
    
    
    def test5():
        global g_num
        mutex.acquire()
        for i in range(1000000):
            g_num += 1
        mutex.release()
        print(g_num)
    
    
    def main():
        t1 = threading.Thread(target=test1)
        t2 = threading.Thread(target=test2)
        # args指定将来调用 函数的时候 传递什么数据过去
        t3 = threading.Thread(target=test3, args=(g_nums,))
        t4 = threading.Thread(target=test4)
        t5 = threading.Thread(target=test5)
        t1.start()
        t2.start()
        t3.start()
        t4.start()
        t5.start()
        # 可以打印当前程序有多少个线程(下面调用返回一个列表)
        print(threading.enumerate())
        time.sleep(5)
        print(g_num)
    
    
    if __name__ == '__main__':
        main()
  • 相关阅读:
    (HDOJ 2503)a/b + c/d
    用VSTS进行网站压力测试
    .NET中IDisposable接口的基本使用
    创建ASP.Net自定义控件
    petshop4.0详解
    .net中SQL防注入代码
    petshop4 缓存机智在sql2005上的设置
    Asp.net自定义控件:概念
    .Net pet shop 4 和 MSMQ
    .net缓存自己总结的几条
  • 原文地址:https://www.cnblogs.com/duxie/p/11336554.html
Copyright © 2011-2022 走看看