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 中文字符串的处理实现代码
Oct 25 Python
Python StringIO模块实现在内存缓冲区中读写数据
Apr 08 Python
pycharm远程调试openstack的图文教程
Nov 21 Python
对python添加模块路径的三种方法总结
Oct 16 Python
简单了解Python3里的一些新特性
Jul 13 Python
Python类中的魔法方法之 __slots__原理解析
Aug 26 Python
python日志模块logbook使用方法
Sep 19 Python
python使用itchat模块给心爱的人每天发天气预报
Nov 25 Python
如何使用Python多线程测试并发漏洞
Dec 18 Python
Python3-异步进程回调函数(callback())介绍
May 02 Python
Python发送邮件封装实现过程详解
May 09 Python
在Windows下安装配置CPU版的PyTorch的方法
Apr 02 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
PHP之变量、常量学习笔记
2008/03/27 PHP
php判断对象是派生自哪个类的方法
2015/06/20 PHP
关于this和self的使用说明
2010/08/01 Javascript
JsDom 编程小结
2011/08/09 Javascript
js 事件截取enter按键页面提交事件示例代码
2014/03/04 Javascript
JavaScript中的数值范围介绍
2014/12/29 Javascript
jQuery插件HighCharts绘制2D柱状图、折线图的组合双轴图效果示例【附demo源码下载】
2017/03/09 Javascript
微信小程序 flex实现导航实例详解
2017/04/26 Javascript
nodeJS微信分享
2017/12/20 NodeJs
js登录滑动验证的实现(不滑动无法登陆)
2018/01/03 Javascript
微信小程序实现图片上传功能实例(前端+PHP后端)
2018/01/10 Javascript
微信小程序首页的分类功能和搜索功能的实现思路及代码详解
2018/09/11 Javascript
如何能分清npm cnpm npx nvm
2019/01/17 Javascript
Vue 组件注册实例详解
2019/02/23 Javascript
vue-router为激活的路由设置样式操作
2020/07/18 Javascript
vue中watch和computed的区别与使用方法
2020/08/23 Javascript
浅谈Python数据类型判断及列表脚本操作
2016/11/04 Python
Python正则表达式使用范例分享
2016/12/04 Python
利用numpy实现一、二维数组的拼接简单代码示例
2017/12/15 Python
python微信撤回监测代码
2019/04/29 Python
详解python中eval函数的作用
2019/10/22 Python
python按顺序重命名文件并分类转移到各个文件夹中的实现代码
2020/07/21 Python
Python爬取网站图片并保存的实现示例
2021/02/26 Python
美国艺术和工艺品商店:Hobby Lobby
2020/12/09 全球购物
戴尔荷兰官方网站:Dell荷兰
2020/10/04 全球购物
介绍一下.net和Java的特点和区别
2012/09/26 面试题
商务助理求职信范文
2014/04/20 职场文书
护士长竞聘演讲稿
2014/04/30 职场文书
审计局2014法制宣传日活动总结
2014/11/01 职场文书
采购员岗位职责范本
2015/04/07 职场文书
毕业证明模板
2015/06/19 职场文书
银行求职信怎么写
2019/06/20 职场文书
写作技巧:如何撰写商业计划书
2019/08/08 职场文书
pytorch 权重weight 与 梯度grad 可视化操作
2021/06/05 Python
Python多个MP4合成视频的实现方法
2021/07/16 Python
SQL使用复合索引实现数据库查询的优化
2022/05/25 SQL Server