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

笔记-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

猜你喜欢

转载自www.cnblogs.com/wodeboke-y/p/10101878.html