Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads with decorators

I'm trying to implement threading(with using decorators) to my application, but can't understand some things about locks and managing threads.

import threading

def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
    return run

class A:
    @run_in_thread
    def method1(self):
        for x in range(10000):
            print x


    @run_in_thread
    def method2(self):
        for y in list('wlkefjwfejwiefwhfwfkjshkjadgfjhkewgfjwjefjwe'):
            print y

    def stop_thread(self):
        pass

c = A()
c.method1()
c.method2()
  1. As I understand, method1 and method2 are not synchronized, but synchronizing of that stuff implementing with help of locks. How I can add locks to my decorator-function?

  2. How can I realize method for stopping long threads using decorators?

like image 569
Skiv_mag Avatar asked Jan 09 '13 11:01

Skiv_mag


1 Answers

If you extend the function to

def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
        return t # <-- this is new!
    return run

i. e., let the wrapper function return the created thread, you can do

c = A()
t1 = c.method1()
t1.join() # wait for it to finish
t2 = c.method2()
# ...

i. e, get the thread where the original method runs in, do whatever you want with it (e. g. join it) and only then call the next method.

If you don't need it in a given case, you are free to omit it.

like image 119
glglgl Avatar answered Nov 15 '22 21:11

glglgl