Python多线程汇总

# -*- coding: utf-8 -*-

#!/usr/bin/env python 

# @Time : 2018/6/29 11:26

# @Software: PyCharm

import time

from concurrent.futures import ThreadPoolExecutor

import threading

import multiprocessing

''' 

创建一个最大可容纳max_workers个的线程池

'''

pool1 = ThreadPoolExecutor(max_workers=300)

def return_future_result(message):

    time.sleep(3)

    return message


def go():

    for num in range(1, 10):

    # 往线程池里面加入一个task

    pool1.submit(return_future_result, ("hello"+str(num)))





if __name__ == '__main__':

    # 第一种

    pool = multiprocessing.Pool(processes=10)

    result = []
    
    for i in xrange(60000):

    msg = "hello %d" % (i)

    print i

    if int(i) % int(2000) == 0:

        time.sleep(2)

        result.append(pool.apply_async(return_future_result, (msg,)))


    # 第二种

    try:

        threads = []
    
        t1 = threading.Thread(target=return_future_result, args=(9101,))

        threads.append(t1)

        for port in (1,10):

            threads.append(threading.Thread(target=return_future_result, args=            (int(port[0]),)))

        # 启动

        for n in range(len(threads)):

            threads[n].start()

    except Exception, e:

        print str(e)

    # 第三种

    for num in range(1, 1000):

        print num

        pool1.submit(return_future_result, num)

        if int(num) % int(1000) == 0:

            time.sleep(2)

 

你可能感兴趣的:(Python)