• 进程、线程


    multiprocessing

    from multiprocessing import Pool
    import os,time,random
    
    def long_time_task(name):
        print('run task %s (%s)...'% (name,os.getpid()))
        start = time.time()
        time.sleep(random.random()*3)
        end = time.time()
        print('task %s runs %0.2f seconds'% (name,(end-start)))
    
    if __name__ =='__main__':
        print('parent process %s '% os.getpid())
        p = Pool(4)
        for i in range(5):
            p.apply_async(long_time_task,args=(i,))
        print('waitng for all subprocesses done...')
        p.close()
        p.join()
        print('all subprocesses done')

     threading

    import time,threading
    
    def loop():
        print('thread %s is running...'% threading.current_thread().name)
        n = 0
        while n<5:
            n += 1
            print('thread %s >>>%s'%(threading.current_thread().name,n))
            time.sleep(1)
        print('thread %s ended'% threading.current_thread().name)
    print('thread %s is running...'% threading.current_thread().name)
    t = threading.Thread(target=loop,name='loopThread')
    t.start()
    t.join()
    print('thread %s ended'% threading.current_thread().name)

     lock

    import time,threading
    #假定这是银行存款
    balance = 0
    
    def change_it(n):
        #先存后取,结果应是0
        global balance
        balance += n
        balance -= n
    
    # def run_thread(n):
    #     for i in range(100000):
    #         change_it(n)
    #
    lock = threading.Lock()
    def run_thread(n):
        for i in range(100000):
            #先要获取锁
            lock.acquire()
            try:
                #可以放心改
                change_it(n)
            finally:
                #改完了一定要释放锁
                lock.release()
    
    #
    t1 = threading.Thread(target=run_thread,args=(5,))
    t2 = threading.Thread(target=run_thread,args=(8,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print(balance)
    View Code

     ThreadLocal

    import threading
    
    #创建全局ThreadLocal对象:
    local_school = threading.local()
    
    def process_student():
        #获取当前线程关联的student
        std = local_school.student
        print('hello %s (in %s)'%(std,threading.current_thread().name))
    
    def process_thread(val):
        #绑定ThreadLocal的student
        local_school.student = val
        process_student()
    
    t1 = threading.Thread(target=process_thread,args=('alice',),name='Thread-A')
    t2 = threading.Thread(target=process_thread,args=('bob',),name='Thread-B')
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    View Code
    渐变 --> 突变
  • 相关阅读:
    实验四 决策树算法及应用
    实验三 朴素贝叶斯算法及应用
    实验二 K-近邻算法及应用
    实验一 感知器及其应用
    园区网核心、防火墙、边界出口冗余实验配置
    PNETLab模拟器部署及使用配置
    基于RPS开发模式的可视化设计解决方案
    Python学习手册《Learning Python》
    【转】Windows 64bit下Python环境配置与集成IDE PyCharm
    时间复杂度完美例子---数组最大子序列和
  • 原文地址:https://www.cnblogs.com/lybpy/p/7862977.html
Copyright © 2020-2023  润新知