-1

I want to execute two commands 1st in background and second on top of it.

import time
loop =[ 1,100]
start_time_loop = time.time()
for in loop:
    print i
end_time_loop = time.time()

multi()
   start_time_func = time.time()
   c= 5*2
   end_time_func = time.time()

Loop should run in background while multiplication is done.

I want to prove:

start_time_loop < start_time_func
end_time_func << end_time_loop

Any pointers will be helpful.

3
  • Might help: stackoverflow.com/questions/23100704/… Commented Sep 4, 2015 at 6:55
  • Python can't use run multiple processes natively. Look into the threading module. Commented Sep 4, 2015 at 9:03
  • 1
    Python can use multiple processes - that's what the multiprocessing module does. Commented Sep 4, 2015 at 12:58

1 Answer 1

1

You need to use multiprocessing to do what you want. It basically starts a new (cloned) copy of python in the background.

import time
from multiprocessing import Process


def thing_1():
    """We'll run this in a subprocess."""
    for i in range(10):
        print('thing_1: {}'.format(i))
        # let's make it take a bit longer
        time.sleep(1)


def thing_2():
    """We'll run this as a normal function in the current python process."""
    time.sleep(1)
    c = 5 * 2
    print('thing_2: {}'.format(c))
    # let's make this take a bit longer too
    time.sleep(1)



if __name__ == '__main__':
    # start the first thing running "in the background"
    p = Process(target=thing_1)
    p.start()
    # keep a record of when we started it running
    start_thing_1 = time.time()

    # let's run the other thing
    start_thing_2 = time.time()
    thing_2()
    end_thing_2 = time.time()

    # this will wait for the first thing to finish
    p.join()
    end_thing_1 = time.time()

    print('thing 1 took {}'.format(end_thing_1 - start_thing_1))
    print('thing 2 took {}'.format(end_thing_2 - start_thing_2))

At the end you'll see:

thing 1 took 10.020239114761353
thing 2 took 2.003588914871216

So, while thing_1 is running in the background your local python can carry on doing other things.

You need to use special mechanisms to transfer any information between the two copies of python. And printing will always be a bit weird because you don't really know which copy of python is going to print next.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.