• 多进程记录


    # -*- coding:utf-8 -*-
    import threading,time
    #通过获取锁对象,访问共有数据,最后释放锁来完成一次操作,
    # 一旦某个线程获取了锁,当这个线程被切换时,下个个进程无法获取该公有数据
    def func():
        #开始处理数据
        global n
        lock.acquire() #获取
        a=n+1
        time.sleep(0.00001)
        n =a
        lock.release() #释放
        # 结束处理
        print(n)
    
    if __name__ == '__main__':
        n=0
        lock=threading.Lock()
        li =[]
        start_time = time.time()
        for i in range(500):
            t=threading.Thread(target=func,args=())
            li.append(t)
            t.start()
        for i in li:
            i.join()  #等待子线程全部执行完
        end_time = time.time()-start_time
        print(n,end_time)  #1000
    # -*- coding:utf-8 -*-
    import threading
    import time, random
    def eating():
        print("我饿了-0-")
        event.wait()
        print('去吃饭的路上...')
    
    def makeing():
        print('做饭中...')
        time.sleep(random.randint(1,2))
        print('做好了,快来!')
        event.set()
    
    
    if __name__ == '__main__':
        event=threading.Event()
        t1 = threading.Thread(target=eating)
        t2 = threading.Thread(target=makeing)
        t1.start()
        t2.start()
    
        # 做饭中
        # 做好了,快来...
        # 去吃饭的路上...

    11

    # -*- coding:utf-8 -*-
    import threading,time
    
    def func():
        #开始处理数据
        global n   #可以改变函数外的变量
        a=n+1
        time.sleep(0.0001)
        n =a
        # 结束处理
    
    if __name__ == '__main__':
        n=0
        li =[]
        for i in range(1000):
            t=threading.Thread(target=func,args=())
            li.append(t)
            t.start()
            print(n)  #可能有多个线程同时拿到同一个值,所以会出现大量重复值,这就需要为数据进行加锁
    
        for i in li:
            i.join()  #等待子线程全部执行完,1000个子线程
        print("n:",n)  #155


  • 相关阅读:
    17多校6 HDU
    E. Present for Vitalik the Philatelist 反演+容斥
    HDU
    F. Cowmpany Cowmpensation dp+拉格朗日插值
    hdu6088 组合数+反演+拆系数fft
    任意模数fft
    Codeforces Round #258 (Div. 2)E
    bzoj3670: [Noi2014]动物园
    HDU
    IO-InputStreamReader
  • 原文地址:https://www.cnblogs.com/python-kp/p/12163068.html
Copyright © 2020-2023  润新知