python 在threading中如何处理主进程和子线程的关系


Posted in Python onApril 25, 2020

之前用python的多线程,总是处理不好进程和线程之间的关系。后来发现了join和setDaemon函数,才终于弄明白。下面总结一下。

1.使用join函数后,主进程会在调用join的地方等待子线程结束,然后才接着往下执行。

join使用实例如下:

import time
import random
import threading
 
class worker(threading.Thread):
  def __init__(self): 
    threading.Thread.__init__(self) 
  def run(self):
    t = random.randint(1,10)
    time.sleep(t)
    print "This is " + self.getName() + ";I sleep %d second."%(t)
    
tsk = []
for i in xrange(0,5):
  time.sleep(0.1)
  thread = worker()
  thread.start()
  tsk.append(thread)
for tt in tsk:
  tt.join()
print "This is the end of main thread."

运行结果如下:

# python testjoin.py 
This is Thread-3;I sleep 2 second.
This is Thread-1;I sleep 4 second.
This is Thread-2;I sleep 7 second.
This is Thread-4;I sleep 7 second.
This is Thread-5;I sleep 7 second.
This is the end of main thread.

这里创建了5个子线程,每个线程随机等待1-10秒后打印退出;主线程分别等待5个子线程结束。最后结果是先显示各个子线程,再显示主进程的结果。

2. 如果使用的setDaemon函数,则与join相反,主进程结束的时候不会等待子线程。

setDaemon函数使用实例:

import time
import random
import threading
 
class worker(threading.Thread):
  def __init__(self): 
    threading.Thread.__init__(self) 
  def run(self):
    t = random.randint(1,10)
    time.sleep(t)
    print "This is " + self.getName() + ";I sleep %d second."%(t)
    
tsk = []
for i in xrange(0,5):
  time.sleep(0.1)
  thread = worker()
  thread.setDaemon(True)
  thread.start()
  tsk.append(thread)
print "This is the end of main thread."

这里设置主进程为守护进程,当主进程结束的时候,子线程被中止

运行结果如下:

#python testsetDaemon.py
This is the end of main thread.

3、如果没有使用join和setDaemon函数,则主进程在创建子线程后,直接运行后面的代码,主程序一直挂起,直到子线程结束才能结束。

import time
import random
import threading
 
class worker(threading.Thread):
  def __init__(self): 
    threading.Thread.__init__(self) 
  def run(self):
    t = random.randint(1,10)
    time.sleep(t)
    print "This is " + self.getName() + ";I sleep %d second."%(t)
    
tsk = []
for i in xrange(0,5):
  time.sleep(0.1)
  thread = worker()
  thread.start()
  tsk.append(thread)
print "This is the end of main thread."

运行结果如下:

# python testthread.py 
This is the end of main thread.
This is Thread-4;I sleep 1 second.
This is Thread-3;I sleep 7 second.
This is Thread-5;I sleep 7 second.
This is Thread-1;I sleep 10 second.
This is Thread-2;I sleep 10 second.

补充知识:Python Thread和Process对比

原因:进程和线程的差距(方向不同,之针对这个实例)

# coding=utf-8
import logging
import multiprocessing
import os
import time
from threading import Thread

logging.basicConfig(
  level=logging.INFO,
  format="%(asctime)s 【 %(process)d 】 %(processName)s %(message)s"
)


def func (i):
  # logging.info(f'子:{os.getpid()},\t{i}')
  return f'子:{os.getpid()},\t{i}'


def main (ctx):
  start01 = time.time()
  ts = [Thread(target=func, args=(i,)) for i in range(100)]
  [t.start() for t in ts]
  [t.join() for t in ts]
  end01 = time.time() - start01
  logging.info(f"线程花费的时间:{end01}秒")
  
  start02 = time.time()
  ps = [ctx.Process(target=func, args=(i,)) for i in range(100)]
  [p.start() for p in ps]
  [p.join() for p in ps]
  end02 = time.time() - start02
  logging.info(f"进程花费的时间:{end02}秒")


if __name__ == '__main__':
  # windows 启动方式
  multiprocessing.set_start_method('spawn')
  # 获取上下文
  ctx = multiprocessing.get_context('spawn')
  # 检查这是否是冻结的可执行文件中的伪分支进程。
  ctx.freeze_support()
  main(ctx)

输出:

2019-10-06 14:17:22,729 【 7412 】 MainProcess 线程花费的时间:0.012967586517333984秒
2019-10-06 14:17:25,671 【 7412 】 MainProcess 进程花费的时间:2.9418249130249023秒

以上这篇python 在threading中如何处理主进程和子线程的关系就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现通过shelve修改对象实例
Sep 26 Python
Python实现二分查找算法实例
May 26 Python
Python实现批量读取word中表格信息的方法
Jul 30 Python
Python2.x与Python3.x的区别
Jan 14 Python
Windows和Linux下Python输出彩色文字的方法教程
May 02 Python
python使用json序列化datetime类型实例解析
Feb 11 Python
python使用生成器实现可迭代对象
Mar 20 Python
python 读取视频,处理后,实时计算帧数fps的方法
Jul 10 Python
python MNIST手写识别数据调用API的方法
Aug 08 Python
Python模拟简单电梯调度算法示例
Aug 20 Python
python3学生名片管理v2.0版
Nov 29 Python
python画柱状图--不同颜色并显示数值的方法
Dec 13 Python
Python多线程:主线程等待所有子线程结束代码
Apr 25 #Python
解决python父线程关闭后子线程不关闭问题
Apr 25 #Python
Python标准库:内置函数max(iterable, *[, key, default])说明
Apr 25 #Python
python except异常处理之后不退出,解决异常继续执行的实现
Apr 25 #Python
python 追踪except信息方式
Apr 25 #Python
Python实现捕获异常发生的文件和具体行数
Apr 25 #Python
python IDLE添加行号显示教程
Apr 25 #Python
You might like
Session保存到数据库的php类分享
2011/10/24 PHP
php 使用curl模拟登录人人(校内)网的简单实例
2016/06/06 PHP
Laravel自动生成UUID,从建表到使用详解
2019/10/24 PHP
用javascript实现画板的代码
2007/09/05 Javascript
jQuery 性能优化手册 推荐
2010/02/23 Javascript
探讨JavaScript标签位置的存放与功能有无关系
2016/01/15 Javascript
Highcharts+NodeJS搭建数据可视化平台示例
2017/01/01 NodeJs
基于Nodejs利用socket.io实现多人聊天室
2017/02/22 NodeJs
简易Vue评论框架的实现(父组件的实现)
2018/01/08 Javascript
微信小程序实现传参数的几种方法示例
2018/01/10 Javascript
JS+HTML5 Canvas实现简单的写字板功能示例
2018/08/30 Javascript
详解CommonJS和ES6模块循环加载处理的区别
2018/12/26 Javascript
layer插件实现在弹出层中弹出一警告提示并关闭弹出层的方法
2019/09/24 Javascript
如何在Vue中使localStorage具有响应式(思想实验)
2020/07/14 Javascript
webstorm建立vue-cli脚手架的傻瓜式教程
2020/09/22 Javascript
python抓取网页图片并放到指定文件夹
2014/04/24 Python
python字典多条件排序方法实例
2014/06/30 Python
python爬取网页转换为PDF文件
2018/06/07 Python
使用python itchat包爬取微信好友头像形成矩形头像集的方法
2019/02/21 Python
Python给图像添加噪声具体操作
2019/03/03 Python
python KNN算法实现鸢尾花数据集分类
2019/10/24 Python
Python selenium文件上传下载功能代码实例
2020/04/13 Python
Python进行特征提取的示例代码
2020/10/15 Python
详解基于Facecognition+Opencv快速搭建人脸识别及跟踪应用
2021/01/21 Python
Python创建自己的加密货币的示例
2021/03/01 Python
美国最大的珠宝首饰网上商城:Jewelry.com
2016/07/22 全球购物
澳大利亚网上玩具商店:Mr Toys Toyworld
2018/03/25 全球购物
英国现代家具和照明购物网站:Heal’s
2019/10/30 全球购物
医学求职信
2014/05/28 职场文书
实习协议书
2015/01/27 职场文书
MySQL基础(一)
2021/04/05 MySQL
Go语言使用select{}阻塞main函数介绍
2021/04/25 Golang
vue实现可拖拽的dialog弹框
2021/05/13 Vue.js
vue中利用mqtt服务端实现即时通讯的步骤记录
2021/07/01 Vue.js
Mysql多层子查询示例代码(收藏夹案例)
2022/03/31 MySQL
vue如何使用模拟的json数据查看效果
2022/03/31 Vue.js