Pythonマルチスレッド要約

1469 ワード

# -*- 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)