Skip to content Skip to sidebar Skip to footer

Running Two Lines Of Code In Python At The Same Time?

How would I run two lines of code at the exact same time in Python 2.7? I think it's called parallel processing or something like that but I can't be too sure. I'm asking here beca

Solution 1:

You can use either multi threading or multiprocessing.

You will need to use queues for the task.

The sample code below will help you get started with multi threading.

import threading
import Queue
import datetime
import time

classmyThread(threading.Thread):
    def__init__(self, in_queue, out_queue):
        threading.Thread.__init__(self)
        self.in_queue = in_queue
        self.out_queue = out_queue

    defrun(self):
        whileTrue:
            item = self.in_queue.get() #blocking till something is available in the queue#run your lines of code here
            processed_data = item + str(datetime.now()) + 'Processed'
            self.out_queue.put(processed_data)


IN_QUEUE = Queue.Queue()
OUT_QUEUE = Queue.Queue()

#starting 10 threads to do your work in parallel for i inrange(10):
    t = myThread(IN_QUEUE, OUT_QUEUE)
    t.setDaemon(True)
    t.start()

#now populate your input queuefor i inrange(3000):
    IN_QUEUE.put("string to process")

whilenot IN_QUEUE.empty():
    print"Data left to process - ", IN_QUEUE.qsize()
    time.sleep(10)

#finally printing outputwhilenot OUT_QUEUE.empty():
    print OUT_QUEUE.get()

This script starts 10 threads to process a string. Waits till the input queue has been processed, then prints the output with the time of processing.

You can define multiple classes of threads for different kinds of processing. Or you put function objects in the queue and have different functions running in parallel.

Solution 2:

It depends on what you mean by at the exact same time. If you want something that doesn't stop while something else that takes a while runs, threads are a decent option. If you want to truly run two things in parallel, multiprocessing is the way to go: http://docs.python.org/2/library/multiprocessing.html

Solution 3:

if you mean for example start a timer and start a loop and exactly after that, I think you can you ; like this: start_timer; start_loop in one line

Solution 4:

there is a powerful package to run parallel jobs using python: use JobLib.

Post a Comment for "Running Two Lines Of Code In Python At The Same Time?"