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使用gensim计算文档相似性
Apr 10 Python
Python中异常重试的解决方案详解
May 05 Python
详解tensorflow实现迁移学习实例
Feb 10 Python
Python实现爬虫设置代理IP和伪装成浏览器的方法分享
May 07 Python
解决pycharm py文件运行后停止按钮变成了灰色的问题
Nov 29 Python
Python设计模式之外观模式实例详解
Jan 17 Python
PyQt QListWidget修改列表项item的行高方法
Jun 20 Python
Django实现auth模块下的登录注册与注销功能
Oct 10 Python
python构造函数init实例方法解析
Jan 19 Python
python cv2.resize函数high和width注意事项说明
Jul 05 Python
Python rabbitMQ如何实现生产消费者模式
Aug 24 Python
pip已经安装好第三方库但pycharm中import时还是标红的解决方案
Oct 09 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+mysqli事务控制实现银行转账实例
2015/01/29 PHP
使用tp框架和SQL语句查询数据表中的某字段包含某值
2019/10/18 PHP
dojo 之基础篇(三)之向服务器发送数据
2007/03/24 Javascript
javascript学习笔记(七) js函数介绍
2012/06/19 Javascript
解决jquery异步按一定的时间间隔刷新问题
2012/12/10 Javascript
javascript中对Attr(dom中属性)的操作示例讲解
2013/12/02 Javascript
JS调用页面表格导出excel示例代码
2014/03/18 Javascript
JavaScript实现的石头剪刀布游戏源码分享
2014/08/22 Javascript
详谈JavaScript内存泄漏
2014/11/14 Javascript
在AngularJS应用中实现一些动画效果的代码
2015/06/18 Javascript
使用Raygun来自动追踪AngularJS中的异常
2015/06/23 Javascript
详解JavaScript的AngularJS框架中的作用域与数据绑定
2016/03/04 Javascript
javascript设计模式之module(模块)模式
2016/08/19 Javascript
浅谈React 属性和状态的一些总结
2016/11/21 Javascript
js/jq仿window文件夹框选操作插件
2017/03/08 Javascript
vue-swiper的使用教程
2018/08/30 Javascript
Node.js中读取TXT文件内容fs.readFile()用法
2018/10/10 Javascript
Bootstrap告警框(alert)实现弹出效果和短暂显示后上浮消失的示例代码
2020/08/27 Javascript
[56:00]2018DOTA2亚洲邀请赛 4.6 淘汰赛 VP vs TNC 第二场
2018/04/10 DOTA
python七夕浪漫表白源码
2019/04/05 Python
python中利用numpy.array()实现俩个数值列表的对应相加方法
2019/08/26 Python
使用python实现多维数据降维操作
2020/02/24 Python
python GUI库图形界面开发之PyQt5简单绘图板实例与代码分析
2020/03/08 Python
Pygame的程序开始示例代码
2020/05/07 Python
解决Keras 自定义层时遇到版本的问题
2020/06/16 Python
深入浅出CSS3 background-clip,background-origin和border-image教程
2011/01/27 HTML / CSS
用HTML5实现网站在windows8中贴靠的方法
2013/04/21 HTML / CSS
HTML5实现移动端点击翻牌功能
2020/10/23 HTML / CSS
热门专业求职信
2014/05/24 职场文书
企业优秀员工事迹材料
2014/05/28 职场文书
团队口号大全
2014/06/06 职场文书
医学专业自荐信
2014/06/14 职场文书
酒店仓管员岗位职责
2015/04/01 职场文书
建党伟业电影观后感
2015/06/01 职场文书
Pandas数据类型之category的用法
2021/06/28 Python
Python开发五子棋小游戏
2022/05/02 Python