笔记-python-多线程-深入-1

1.      线程池

1.1.    线程池:控制同时存在的线程数量

threading没有线程池,只能自己控制线程数量。

基本有两种方式:

  1. 每间隔一段时间创建一批线程
  2. 加一层循环,进行条件判断,如果线程数量小于预定值则创建新线程,否则等待;

使用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的更多相关文章

  1. Python 爬虫笔记、多线程、xml解析、基础笔记(不定时更新)

    1  Python学习网址:http://www.runoob.com/python/python-multithreading.html

  2. Python Web学习笔记之多线程编程

    本次给大家介绍Python的多线程编程,标题如下: Python多线程简介 Python多线程之threading模块 Python多线程之Lock线程锁 Python多线程之Python的GIL锁 ...

  3. Python多线程及其使用方法

    [Python之旅]第六篇(三):Python多线程及其使用方法   python 多线程 多线程使用方法 GIL 摘要: 1.Python中的多线程     执行一个程序,即在操作系统中开启了一个进 ...

  4. python多线程学习记录

    1.多线程的创建 import threading t = t.theading.Thread(target, args--) t.SetDeamon(True)//设置为守护进程 t.start() ...

  5. python多线程编程

    Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join( ...

  6. Python 多线程教程:并发与并行

    转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...

  7. python多线程

    python多线程有两种用法,一种是在函数中使用,一种是放在类中使用 1.在函数中使用 定义空的线程列表 threads=[] 创建线程 t=threading.Thread(target=函数名,a ...

  8. python 多线程就这么简单(转)

    多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识. 单线程 在好些年前的 ...

  9. 孙鑫VC学习笔记:多线程编程

    孙鑫VC学习笔记:多线程编程 SkySeraph Dec 11st 2010  HQU Email:zgzhaobo@gmail.com    QQ:452728574 Latest Modified ...

  10. python 多线程就这么简单(续)

    之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思.因为我们在使用电脑的过程中无时无刻都在多进程和多线程.我们可以接着之前的例子继续讲.请先看我的上一篇博客. python 多线程就这 ...

随机推荐

  1. 移动webApp - 1像素实现(点5像素的秘密)

    在移动web项目中,经常会实现以下1像素的边框 移动web设计中,在retina显示屏下网页会由1px会被渲染为2px,那么视觉稿中1px的线条还原成网页需要css定义为0.5px 但是正当我们去用0 ...

  2. Android Process & Thread

    Native Service and Android Service Native Service:In every main() method of NativeService, which is ...

  3. selenium googleDrive

    http://chromedriver.storage.googleapis.com/index.html?path=2.1/下载地址 把googledriver.exe 放到google浏览器下目录 ...

  4. DIV命名规范

    DIV命名规范 企业DIV使用频率高的命名方法 网页内容类 --- 注释的写法: /* Footer */ 内容区/* End Footer */ 摘要: summary 箭头: arrow 商标:  ...

  5. MVC:控制器名与被调用模型名称发生冲突的解决方案

    控制器名与被调用的模型名发生了冲突: 有两种解决方案: (1)将被调用的模型类名进行修改 例如: (2)对被调用的模型进行起一个别名 以上 加油ヾ(◍°∇°◍)ノ゙

  6. py常见模块

    1.系统相关的信息模块: import sys sys.argv 是一个 list,包含所有的命令行参数. sys.stdout sys.stdin sys.stderr 分别表示标准输入输出,错误输 ...

  7. Performing User-Managed Database-18.5、Restoring Control Files

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/offbeatmine/article/details/28429339 18.5.Restoring ...

  8. 2017.11.18 C语言的算法分析题目

    算法分析 1. 选定实验题目,仔细阅读实验要求,设计好输入输出,按照分治法的思想构思算法,选取合适的存储结构实现应用的操作. 2. 设计的结果应在Visual C++ 实验环境下实现并进行调试.(也可 ...

  9. Unable to launch the Java Virtual Machine

    看看国内的回答,http://zhidao.baidu.com/question/119993351.html 再看看国外的,http://www.mkyong.com/oracle/oracle-s ...

  10. 跑groud truth的disparity

    1.用这个初始化cv::Mat M(375,1242,CV_32FC1,0.0); ,就会报以下的错误: malloc(): memory corruption: 0x000000000165df40 ...