笔记-python-多线程-深入-1
笔记-python-多线程-深入-1
1. 线程池
1.1. 线程池:控制同时存在的线程数量
threading没有线程池,只能自己控制线程数量。
基本有两种方式:
- 每间隔一段时间创建一批线程
- 加一层循环,进行条件判断,如果线程数量小于预定值则创建新线程,否则等待;
使用queue,条件判断都属于这种方式。
# 线程函数1
def th(num=3):
print('{} enter th:{}'.format(num,
threading.get_ident()))
print('the main thread
is:{}'.format(threading.main_thread()))
print('th:active thread\'s num is
{}'.format(threading.active_count()))
time.sleep(5)
print('th end',num)
# 方式1:一批批创建
def multithreads1(*args):
print('enter multithreads1')
t_list = list()
for _ in range(7):
t_list.append(threading.Thread(target=th, args=(_,),name= 'aaa'))
for _ in t_list:
_.daemon = True
_.start()
print('from
multithreads:',threading.get_ident(),threading.activeCount())
#print('active
threads:',threading.enumerate())
'''
for _ in t_list:
print(type(_))
_.join()
'''
t_list = threading.enumerate()
print(type(t_list))
print('t_list:',t_list)
for _ in t_list:
if _.name == 'aaa':
_.join()
print('main thread end.')
# 方式2:控制总任务数,每次循环检查活动线程数,如果较少则创建新线程
# 通过信号量/变量条件控制总循环次数
def multithreads2(task_nums=100, max_threads=5, *args):
task_i = 0
while task_i < task_nums:
if threading.active_count() <
max_threads:
t =
threading.Thread(target=th, args=(task_i,))
t.daemon = True
t.start()
else:
time.sleep(2)
'''
# 测active_count()
print('this is in mainthread:\nthread num is {},thread id is
{}'.format(threading.activeCount(),threading.get_ident()))
#th(3)
multithreads1()
print('main_thread stop:{}'.format(threading.current_thread()))
'''
# 线程调用函数
import queue
def th1(num=-1):
print('enter th1.',num)
time.sleep(3)
print('end th1.',num)
# 方式3:
def multithreads3(*args):
print('enter multithreads3!')
q = queue.Queue()
for i in range(3):
q.put(i)
thread_num_max = 10
while True:
if threading.active_count() <=
thread_num_max:
proxy = q.get()
if proxy is None:
print('break')
break
thread_t =
threading.Thread(target=th1, args=(proxy,))
thread_t.deamon = True
thread_t.start()
t_list = threading.enumerate()
for _ in t_list:
if _ is
threading.current_thread():
pass
else:
_.join()
print('active thread number:',threading.active_count())
总结:
1.可以对死亡线程进行join
2.一定要注意join方式,否则容易成为单线程。
3.activecount 包括主线程,是进程内所有的线程数。
2.
线程返回运行结果
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
笔记-python-多线程-深入-1的更多相关文章
- Python 爬虫笔记、多线程、xml解析、基础笔记(不定时更新)
1 Python学习网址:http://www.runoob.com/python/python-multithreading.html
- Python Web学习笔记之多线程编程
本次给大家介绍Python的多线程编程,标题如下: Python多线程简介 Python多线程之threading模块 Python多线程之Lock线程锁 Python多线程之Python的GIL锁 ...
- Python多线程及其使用方法
[Python之旅]第六篇(三):Python多线程及其使用方法 python 多线程 多线程使用方法 GIL 摘要: 1.Python中的多线程 执行一个程序,即在操作系统中开启了一个进 ...
- python多线程学习记录
1.多线程的创建 import threading t = t.theading.Thread(target, args--) t.SetDeamon(True)//设置为守护进程 t.start() ...
- python多线程编程
Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join( ...
- Python 多线程教程:并发与并行
转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...
- python多线程
python多线程有两种用法,一种是在函数中使用,一种是放在类中使用 1.在函数中使用 定义空的线程列表 threads=[] 创建线程 t=threading.Thread(target=函数名,a ...
- python 多线程就这么简单(转)
多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识. 单线程 在好些年前的 ...
- 孙鑫VC学习笔记:多线程编程
孙鑫VC学习笔记:多线程编程 SkySeraph Dec 11st 2010 HQU Email:zgzhaobo@gmail.com QQ:452728574 Latest Modified ...
- python 多线程就这么简单(续)
之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思.因为我们在使用电脑的过程中无时无刻都在多进程和多线程.我们可以接着之前的例子继续讲.请先看我的上一篇博客. python 多线程就这 ...
随机推荐
- 最小正子序列(序列之和最小,同时满足和值要最小)(数据结构与算法分析——C语言描述第二章习题2.12第二问)
#include "stdio.h" #include "stdlib.h" #define random(x) (rand()%x) void creat_a ...
- Python基础学习之文件(1)
1.文件对象 文件对象不仅可以用来访问普通的磁盘文件,还可以访问具有文件类型接口的其他对象;文件只是连续的字节序列. 2.文件内建函数(open()) 内建函数open()是打开文件的"钥匙 ...
- Docker cgroup.procs no space left on device
环境:centos6 运行docker 时 错误提示: System error: write /sys/fs/cgroup/docker/01f5670fbee1f6687f58f3a943b1e1 ...
- April 26 2017 Week 17 Wednesday
We read the world wrong and say that it deceives us. 我们把世界看错了,反而说它欺骗了我们. It is not a cakewalk to see ...
- IOS 计算文字尺寸(UILabel)
方式1 :普通用法 #define MJNameFont [UIFont systemFontOfSize:14] /** * 计算文字尺寸 * * @param text 需要计算尺寸的文字 * ...
- 使用命令创建jenkins的job,解决jenkinsapi.custom_exceptions.JenkinsAPIException错误
如果你使用 Python 2.7.12,Jenkins版本为Jenkins ver. 2.22,你使用我上面一种提到的修改的以下代码可以进行Jenkins的job复制 http://www.cnblo ...
- MySQL 主从同步 Slave_IO_Running: No
MariaDB [chen]> show slave status \G *************************** 1. row ************************* ...
- python doctest测试
title: Python doctest测试 tags: Python --- doctest测试 python 提供了REPL(read-eval-print loop,读取.求值.输出的循环) ...
- 第6章 新建工程-寄存器版—零死角玩转STM32-F429系列
第6章 新建工程—寄存器版 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/fireg ...
- open cv & vs
原来基于vs和msdn一起读视频,结果发现现在的函数不能用了.找不到合适的解码器了,只好转战opencv. 具体怎么用,网上查吧,不过opencv读视频的例子,可以见这个. http://blog.c ...