Runpeng Chen
Runpeng Chen

Reputation: 105

how to do async in python?

There is function which need to sleep 10 second. But in the meantime, I don't want it to block my main function. How to deal with that? I try to do like that. However, it still block my main function.

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";

the main function will call this function.

Upvotes: 0

Views: 130

Answers (2)

RobertB
RobertB

Reputation: 1929

Not sure why you are using Pool. You are spawning 2 subprocesses to send a single email? What about just spawning a single process. The following should get you started. (I put a "sleep(30)" where you would actually call send_mail)

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()

Upvotes: 0

James
James

Reputation: 2834

pool.join();

is your blocker. remove it to not block.

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

EDIT:

import threading 

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

Upvotes: 1

Related Questions