zoukankan      html  css  js  c++  java
  • python3学习笔记(三)多线程与多进程

    线程thread,库threading

    进程process,库Process

    使用起来方法跟其他语言相似,也不需要下载其他的库,语言自带的库里就有

    1.多线程的例子

     1 #coding=utf-8
     2 import threading
     3 from time import sleep, ctime
     4 
     5 loops = [1, 2]
     6 
     7 def loop(nloop, nsec):
     8     print('start loop', nloop, 'at:', ctime())
     9     sleep(nsec)
    10     print('loop', nloop, 'done at:', ctime())
    11 
    12 
    13 
    14 def main():
    15     print('starting at:', ctime())
    16     threads = []
    17     nloops = range(len(loops))  # nloops=1,2
    18 
    19     for i in  nloops:
    20         t = threading.Thread(target=loop, args=(i, loops[i]))
    21         threads.append(t)
    22 
    23     for i in nloops:
    24         threads[i].start()
    25 
    26     for i in nloops:
    27         threads[i].join()
    28 
    29     print('all end', ctime())
    30 
    31 
    32 if __name__ == '__main__':   #Make a script both importable and executable
    33     main()
    View Code

    2.多进程的例子

     1 #coding=utf-8
     2 from multiprocessing import  Process
     3 import os
     4 
     5 def info(title):
     6     print(title)
     7     print('module name:', __name__)
     8     if hasattr(os, 'getppid'):
     9         print('parent process:', os.getppid())    #父进程id
    10     print('process id:', os.getpid())    #进程自己的id
    11 
    12 
    13 def f(name):
    14     info('function f')
    15     print('hello', name)
    16 
    17 #如果本进程A创建了一个进程B 那么B是A的子进程   A是B的父进程
    18 if __name__ == '__main__':
    19     info('main process')
    20     p = Process(target=f, args=('ks', ))
    21     p.start()
    22     p.join()
    View Code
  • 相关阅读:
    限制页面只能在框架页中
    Excel导入的HDR=YES; IMEX=1详解
    ASP复制文件
    C#获取当前日期时间
    SQL语句添加删除修改字段
    C#代码调用页面javascript函数
    JavaScript 层
    vue-router实现SPA购物APP基本功能
    iOS自定义从底部弹上来的View
    RabbitMQ消息队列生产者和消费者
  • 原文地址:https://www.cnblogs.com/ikel/p/8081898.html
Copyright © 2011-2022 走看看