美文网首页
Python多任务_线程

Python多任务_线程

作者: Lutous | 来源:发表于2020-03-12 16:53 被阅读0次
    简单使用
    import threading
    import time
    
    
    class MyThread(threading.Thread):
        def run(self):
            for i in range(3):
                time.sleep(1)
                print "I'm" + self.name + '@' + str(i)
    
    
    def test():
        for i in range(5):
            MyThread().start()
    
    多线程共享全局变量-互斥锁
    import threading
    import time
    
    
    g_num = 0
    
    
    def work1(num):
        global g_num
        for i in range(num):
            mutex.acquire()
            g_num += 1
            mutex.release()
        print("------ in work1, g_num is %d ------" % g_num)
    
    
    def work2(num):
        global g_num
        for i in range(num):
            mutex.acquire()
            g_num += 1
            mutex.release()
        print "------ in work2, g_num is %d ------" % g_num
    
    
    print "--- 创建线程之前 g_num is %d ---" % g_num
    
    # 创建一个互斥锁
    # 默认是未上锁的状态
    mutex = threading.Lock()
    
    t1 = threading.Thread(target=work1, args=(10000,))
    
    t2 = threading.Thread(target=work2, args=(10000,))
    
    t1.start()
    t2.start()
    
    print threading.enumerate()
    while len(threading.enumerate()) != 1:
        time.sleep(1)
    
    print "--- 创建线程之后 g_num is %d ---" % g_num
    

    相关文章

      网友评论

          本文标题:Python多任务_线程

          本文链接:https://www.haomeiwen.com/subject/yylmjhtx.html