python 多线程实验

from multiprocessing import Pool
from multiprocessing import cpu_count
import time


def son_do(flag):
    for i in range(2):
        time.sleep(1)
        print 'son thread'
    if flag == 5:
        raise ValueError('sorry I am a selfexception')


def do(flag):
    try:
        son_do(flag=flag)
    except Exception, e:
        print e.args[0]
        print e

    return True


if __name__ == '__main__':
    pool = Pool(processes=max(1, cpu_count() / 2))
    results = []
    for i in range(10):
        print '%s thread ' % i
        result = pool.apply_async(do, args=(i,))
        results.append(result)

    pool.close()
    pool.join()
    # for result in results:
    #     # this can block the main thread
    #     print result.get()

    print 'main thread'

    # do(5)

 

posted @ 2017-09-19 15:00  百变小超  阅读(244)  评论(0编辑  收藏  举报