笔记-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. Sublime Text Emmet插件 : 生成html,css 快捷键

    (输入下面简写,按Tab键可触发效果,或者 ctrl + e) html缩写 输入 !后 按下 ctrl + e : 结果 <!DOCTYPE html><html lang=&qu ...

  2. react-native —— 在Mac上搭建React Native Android开发环境

    需要:JDK,Android SDK,Node.js   1.安装JDK 去Java官网下载列表选择Mac OS X x64版   2.安装Android SDK 虽然现在谷歌推荐使用Android ...

  3. .net 使用Memcached

    1.创建个人MemcachedHelper类 /// <summary> /// 页 面 名:缓存管理类<br/> /// 说 明:设置.获取.移除Cache<br/&g ...

  4. Struts2_结果类型_resulttype_1

    看下面的例子: 一般使用4种:dispatcher(容器内跳转到JSP页面).redirect(重定向到jsp页面).chain(容器内跳转到另一个Action).redirectAction(重定向 ...

  5. 关于 supersocket 不能通过Bootstrap 启动

    App.config内容   <configSections> <section name="superSocket" type="SuperSocke ...

  6. Linux改变文件属性与权限

    chgrp:改变文件所属用户组 chown:改变文件所有组 chmod:改变文件的权限 一.chgrp(change group的简称) 修改文件所属组:eg:chgrp users install. ...

  7. Win10技巧:使用“照片”应用剪辑视频、添加特效

    Win10内置了很多实用的应用,你不仅可以通过“Win键+G”快速录制电脑屏幕,如软件操作.游戏界面等,你还可以利用“照片”应用来对视频进行快速的剪辑,把录制前后多余的内容去除,同时你也可以对游戏中的 ...

  8. Javascript打印金字塔,倒立金字塔,空心金字塔,菱形,空心菱形等

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. ABAP Netweaver和Hybris里获得内存使用统计数据

    ABAP Netweaver 事物码ST06 Hybris 每隔5秒钟,Hybris Administration console会发起一个到Java后台的AJAX查询请求: 这个5秒的时间间隔定义在 ...

  10. linux下安装mysql并修改密码

    删除已有mysql并重新安装mysql 查看是否已安装过mysql rpm -qa |grep -i mysql 2.移除安装的包 (在之前如果有启动mysql最好关掉服务) 使用rpm –ev 包名 ...