欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

py 多线程 多进程 异步调用 回调 dummy封装threads 总结

程序员文章站 2022-05-24 14:30:28
...

        #coding:utf-8


'''
多进程同步写法
'''
from multiprocessing import Process
import time,os,sys,math

def f(name):
    print 'hello',name
    print os.getppid()
    print os.getpid()
    sys.stdout.flush()

def main():
    process_list = []
    for i in range(10):
        p = Process(target=f,args=(i,))
        p.start()
        process_list.append(p)
    for j in process_list:
        j.join()


main()

'''
进程池+异步调用+回调
'''
import time
from multiprocessing import Pool
def ff(x):
    print x
    return x
def ee(*args):
    print args

for i in xrange(3):
    pool = Pool(processes=4)
    result = pool.apply_async(ff,[i],callback=ee)
    time.sleep(2)
    pool.close()
    pool.join()


'''
多线程写法
'''
import  threading

def th():
    print 'hello 1'
threading.Event(3)
    print 'hello 2'
t = threading.Thread(name='th',target=th,args=())
t.daemon = True
t.start()

'''
dummy.map封装多线程
'''
from multiprocessing.dummy import Pool as ThreadPool
def threads(functions,queue):

    # 创建一个工作者线程池
pool = ThreadPool(3)
    # 在各个线程中打开url,并返回结果
results = pool.map(functions,queue)
    # 关闭线程池,等待工作结束
pool.close()
    pool.join()
    return results