• 多线程、进程


    import threading,time
    def run():
    time.sleep(3) #干活需要3s
    print('哈哈哈')
    # for i in range(5): #串行
    # run()
    # for i in range(5):
    # t = threading.Thread(target=run) #实例化了一个线程
    # t.start()
    #多线程, 就是N个线程一起在干活




    #1、串行
    # start_time = time.time()
    # for k,v in urls.items():
    # down_html(k,v)
    # end_time = time.time()
    # run_time = end_time - start_time
    # print('下载总共花了xxx时间',run_time)


    #2、并行
    urls = {
    'besttest':'http://www.besttest.cn',
    'niuniu':'http://www.nnzhp.cn',
    'dsx':'http://www.imdsx.cn',
    'cc':'http://www.cc-na.cn'
    }
    import requests,time
    data= {}
    def down_html(file_name,url):
    start_time = time.time()
    res = requests.get(url).content
    open(file_name+'.html','wb').write(res)
    end_time = time.time()
    run_time = end_time-start_time
    data[url] = run_time
    threads = []
    start_time = time.time()
    for k,v in urls.items(): #5次
    t = threading.Thread(target=down_html,args=(k,v)) #多线程的函数如果传参的话,必须得用args
    t.start()
    threads.append(t)
    #6个线程
    #进程里面默认有一个线程,这个线程叫做主线程
    for t in threads:
    t.join()

    print(data)
    end_time = time.time()
    run_time = end_time - start_time
    print('下载总共花了xxx时间',run_time)



    多线程等待
    import threading,time
    def run():
    # time.sleep(3)
    print('哈哈哈')
    start_time = time.time()
    threads = [] #存放启动的5个线程
    for i in range(5):
    t = threading.Thread(target=run)
    t.start()#
    threads.append(t)

    for lyl in threads: #主线程循环等待5个子线程执行结束
    lyl.join()
    end_time = time.time()
    print('run_time..',end_time-start_time)


    多进程
    import multiprocessing,threading

    def my():
    print('哈哈哈')

    def run(num):
    for i in range(num):
    t = threading.Thread(target=my)
    t.start()
    if __name__ == '__main__':
    for i in range(5):
    p = multiprocessing.Process(target=run,args=(6,)) #启动一个进程
    p.start()

    守护线程
    import threading,time

    def run():
    time.sleep(3)
    print('哈哈哈')

    for i in range(50):
    t = threading.Thread(target=run)
    t.setDaemon(True) #把子线程设置成为守护线程
    t.start()

    print('Done,运行完成。')
    time.sleep(3)
  • 相关阅读:
    数据仓库-数据清洗
    数据仓库-维度模型(模型类型、建模过程)
    数据仓库-维度
    I am going to India on a business trip
    Android O编译前修改文件和目录权限
    apktool介绍
    Android中国官网资源网站
    android7.0后对于detected problems with app native libraries提示框显示
    android7.0后对于file://的限制
    android7.0对于SharedPreferences设置模式的限制
  • 原文地址:https://www.cnblogs.com/irisx/p/9111970.html
Copyright © 2020-2023  润新知