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写的一个squid访问日志分析的小程序
Sep 17 Python
Python中的下划线详解
Jun 24 Python
基于Python实现的ID3决策树功能示例
Jan 02 Python
Python-OpenCV基本操作方法详解
Apr 02 Python
python方法生成txt标签文件的实例代码
May 10 Python
Python中存取文件的4种不同操作
Jul 02 Python
Python实现的连接mssql数据库操作示例
Aug 17 Python
Pandas库之DataFrame使用的学习笔记
Jun 21 Python
Python中 Global和Nonlocal的用法详解
Jan 20 Python
django model的update时auto_now不被更新的原因及解决方式
Apr 01 Python
基于python获取本地时间并转换时间戳和日期格式
Oct 27 Python
Python Django模型详解
Oct 05 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
重料打造自己的“宝马”---第三代
2021/03/02 无线电
使用JSON实现数据的跨域传输的php代码
2011/12/20 PHP
PHP版网站缓存加快打开速度的方法分享
2012/06/03 PHP
php上传apk后自动提取apk包信息的使用(示例下载)
2013/04/26 PHP
php float不四舍五入截取浮点型字符串方法总结
2013/10/28 PHP
从零开始学YII2框架(二)通过 Composer 安装扩展插件
2014/08/20 PHP
PHP实现对xml的增删改查操作案例分析
2017/05/19 PHP
Ajax请求PHP后台接口返回信息的实例代码
2018/08/21 PHP
类似框架的js代码
2006/11/09 Javascript
Javascript入门学习资料收集整理篇
2008/07/06 Javascript
ASP Json Parser修正版
2009/12/06 Javascript
js 优化次数过多的循环 考虑到性能问题
2011/03/05 Javascript
Javascript实现滚动图片新闻的实例代码
2013/11/27 Javascript
DOM 事件流详解
2015/01/20 Javascript
JS轮播图中缓动函数的封装
2020/11/25 Javascript
详解Vue-基本标签和自定义控件
2017/03/24 Javascript
详解升级react-router 4 踩坑指南
2017/08/14 Javascript
微信小程序picker组件简单用法示例【附demo源码下载】
2017/12/05 Javascript
Vue设置长时间未操作登录自动到期返回登录页
2020/01/22 Javascript
python2.7删除文件夹和删除文件代码实例
2013/12/18 Python
Python编程中time模块的一些关键用法解析
2016/01/19 Python
对python中两种列表元素去重函数性能的比较方法
2018/06/29 Python
Pytorch中膨胀卷积的用法详解
2020/01/07 Python
Python pip安装第三方库实现过程解析
2020/07/09 Python
pandas使用函数批量处理数据(map、apply、applymap)
2020/11/27 Python
韩国著名的在线综合购物网站:Akmall
2016/08/07 全球购物
工作失误检讨书范文大全
2014/01/13 职场文书
五一手机促销方案
2014/03/08 职场文书
股东合作协议书范本
2014/04/14 职场文书
合伙经营协议书
2014/04/18 职场文书
企业金融服务方案
2014/06/03 职场文书
个人作风建设剖析材料
2014/10/11 职场文书
财务工作检讨书
2014/10/29 职场文书
2015年领导干部廉洁自律工作总结
2015/05/26 职场文书
《原神》新角色演示“神里绫人:林隐泓洄” 宠妹狂魔
2022/04/03 其他游戏
利用Python实现翻译HTML中的文本字符串
2022/06/21 Python