装饰线程 [英] Threads with decorators

查看:56
本文介绍了装饰线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在应用程序中实现线程化(使用装饰器),但无法理解有关锁和管理线程的某些知识。

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. 据我了解,method1和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?

如何实现使用装饰器停止长线程的方法?

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


推荐答案

如果将函数扩展到

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。例如,让包装函数返回创建的线程,您可以这样做

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,获取运行原始方法的线程,对它执行任何操作(例如,加入它),然后才调用下一个方法。

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.

这篇关于装饰线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆