michael11
michael11

Reputation: 15

Running python object method in parallel to my other code

I'm trying to figure out a way to run a method of some object in parallel with my main loop.

My goal is to have some loop which reads and pre-processes images, and an object which performs further processing in parallel, without halting the pre-process loop (sort of pipeline?)

I picutred it somehow like this:

class Class1:
   def __init__(self):
      ...
   def run(self, arg1):
      ...

obj1 = Class1()
while(True):
   ...
   << calculate arg1_value >>
   << start executing obj1.method1(arg1_value) and move on>>
   << print results of obj1.method1 (if they are available) >>

Which python parallel processing method should I use? Or should I work with queues?

Upvotes: 0

Views: 60

Answers (1)

ƒkS124
ƒkS124

Reputation: 90

You could use threads. It permits you to do several things in parallel.

import threading
import time


# defining the func that we will use in the thread
def nothing(value):
    global result

    # waiting 5 seconds
    time.sleep(5)

    result = value

result = None
# defining the thread and setting the func as its target
thread = threading.Thread(target=nothing, args=[52])
thread.start()

# this loop will continue until the variable is redefined
# in order to show that you can do other things during the
# processing of the thread
while result is None:

    print("Thread is currently processing")


print(result)

Upvotes: 1

Related Questions