多线程

作者: 疯中 | 来源:发表于2018-04-26 18:32 被阅读0次
# -*- coding: utf-8 -*-
from multiprocessing.dummy import Pool as ThreadPool

import time

def fun(msg):

    print('msg: ', msg)

    time.sleep(1)

    print('********')

    return 'fun_return %s' % msg

# map_async

print('\n------map_async-------')

arg = [1, 2, 10, 11, 18]

async_pool = ThreadPool(processes=4)

result = async_pool.map_async(fun, arg)

print(result.ready()) # 线程函数是否已经启动了

print('map_async: 不堵塞')

result.wait() # 等待所有线程函数执行完毕

print('after wait')

if result.ready(): # 线程函数是否已经启动了

    if result.successful(): # 线程函数是否执行成功

        print(result.get()) # 线程函数返回值

# map

print('\n------map-------')

arg = [3, 5, 11, 19, 12]

pool = ThreadPool(processes=3)

return_list = pool.map(fun, arg)

print('map: 堵塞')

pool.close()

pool.join()

print(return_list)

# apply_async

print('\n------apply_async-------')

async_pool = ThreadPool(processes=4)

results =[]

for i in range(5):

    msg = 'msg: %d' % i

    result = async_pool.apply_async(fun, (msg, ))

    results.append(result)

    print('apply_async: 不堵塞')

    # async_pool.close()

    # async_pool.join()

    for i in results:

        i.wait() # 等待线程函数执行完毕

    for i in results:

        if i.ready(): # 线程函数是否已经启动了

            if i.successful(): # 线程函数是否执行成功

                print(i.get()) # 线程函数返回值

# apply

print('\n------apply-------')

pool = ThreadPool(processes=4)

results =[]

for i in range(5):

    msg = 'msg: %d' % i

    result = pool.apply(fun, (msg, ))

    results.append(result)

    print('apply: 堵塞')

    print(results)

相关文章

  • iOS多线程 NSOperation

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程 pthread、NSThread

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程: GCD

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程运用

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程基础

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • 多线程介绍

    一、进程与线程 进程介绍 线程介绍 线程的串行 二、多线程 多线程介绍 多线程原理 多线程的优缺点 多线程优点: ...

  • iOS进阶之多线程管理(GCD、RunLoop、pthread、

    深入理解RunLoopiOS多线程--彻底学会多线程之『GCD』iOS多线程--彻底学会多线程之『pthread、...

  • iOS多线程相关面试题

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

  • 多线程之--NSOperation

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

  • iOS多线程之--NSThread

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

网友评论

      本文标题:多线程

      本文链接:https://www.haomeiwen.com/subject/fwpmlftx.html