Home Archives Categories Tags

Python 多线程示例

发布时间: 更新时间: 总字数:103 阅读时间:1m 作者: 分享

Python 多线程示例

示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time
import random
from multiprocessing import Pool


def sub_task(name):
    spid = os.getpid()
    print('run sub task name is {}, sub pid is {}...'.format(name, spid))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('sub task %s runs %0.2f seconds.' % (name, (end - start)))
    return spid


if __name__=='__main__':
    print('main process %s.' % os.getpid())
    p = Pool(4)
    results = []
    for i in range(10):
        r = p.apply_async(sub_task, args=(i,))
        results.append(r)
    print('Waiting for all subprocesses done...')

    for r in results:
        print("-- result {}".format(r.get()))
    p.close()
    p.join()
    print('All sub proceess done.')
最新评论
加载中...