如何在python中执行async



有一个函数需要休眠10秒。但与此同时,我不想让它阻碍我的主要功能。如何处理呢?我试着那样做。但是,它仍然阻塞了我的主要功能。

def tester():
   pool.size=2;
   pool=multiprocessing.Pool(pool_size);
   pool.apply_async(send_mail, args=("test",));
   pool.close();
   pool.join();
   print "email is done";

main函数将调用这个函数

pool.join();

是你的阻滞剂。拆下不堵塞。

https://docs.python.org/2/library/multiprocessing.html multiprocessing.Process.join

编辑:

import threading 
print "start"
th = threading.Thread(target=tester)
th.daemon = False
print "thread start"
th.start()
print "executing other code"

不知道为什么要使用Pool。您正在生成2个子进程来发送单个电子邮件?如果只生成一个进程呢?下面的内容可以帮助你开始。(我在实际调用send_mail的地方放了一个"sleep(30)")

from multiprocessing import Process, Queue
from time import sleep
def wrap_send_email(q, msg):
    try:
        sleep(30)
        q.put( [ msg, 'mail sent sucessfully'] )
    except: 
        q.put( [ msg, 'mail not sent successfully'] )

def test():
    q = Queue()
    p = Process(target=wrap_send_email, args=(q, 'test message'))
    p.start()
    while p.is_alive():
        print("Doing stuff while the other process is working.")
        sleep(5)
    print(q.get())
    p.join()

最新更新