加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python_线程读写操作<一>

发布时间:2020-12-20 12:57:33 所属栏目:Python 来源:网络整理
导读:线程读写操作 import threading,random,queue q = queue.Queue() alist = [] def shengchan(): for i in range(10 ): alist.append(random.randint( 1,20 )) q.put(alist) print ( ‘ 随机生成的十个数是%s ‘ % alist) def xiaofei(): with open( ‘ xiabo.

线程读写操作

import threading,random,queue q = queue.Queue() alist=[] def shengchan(): for i in range(10): alist.append(random.randint(1,20)) q.put(alist) print(随机生成的十个数是%s%alist) def xiaofei(): with open(xiabo.txt,w+,encoding=utf8) as f: f.write(str(q.get())) f.seek(0) c =f.read() print(c) if __name__==__main__: t1 = threading.Thread(target=shengchan) t2 = threading.Thread(target=xiaofei) t1.start() t2.start()

进程池相关

from multiprocessing import Pool  # 导入模块进程池
import os,time,random  # 导入windows系统,时间,随机数模块


# print(random.random())
def task(name):  # name是一个形参,先分析函数功能
    print(任务跑在 %s (%d)... % (name,os.getpid()))  # 打印了进程池传的参数i,还有进程编号
    start = time.time()  # 记录一个开始时间
    time.sleep(random.random() * 3)  # 随机0-3之间的数
    # print(random.random()*3) %s 字符串 %d 整型 %f 浮点型
    end = time.time()  # 结束时间
    print(任务 %s 跑了 %0.2f时间 % (name,(end - start)))  # 结束减去开始时间可以得出跑了多长时间算出函数运行时间


if __name__ == __main__:
    print(父进程是%d % os.getpid())  # 获取当前进程编号ID
    p = Pool(4)  # 使用进程池类方法创建了4个进程
    for i in range(1,6):  # 给4个进程分派了5个任务任务编号是1,2,3,4,5
        p.apply_async(task,args=(i,))  # apply_async 是异步非阻塞的。# 让进程池执行了task函数,传的参数是i
    # 意思就是:不用等待当前进程执行完毕,随时根据系统调度来进行进程切换。
    print(等待所有子进程跑完...)
    p.close()  # 关闭进程池,因为后边有join必须保证子进程不再乱跑
    # time.sleep(2)
    # p.join()  # 让所有的进程互相等待大家一起结束回家吃饭
    print(所有的子进程跑完了)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读