Skip to main content
 首页 » 编程设计

python之使用语句和 python 线程

2025年05月04日11myhome

我是 Python 菜鸟,试图了解线程模块。 我正在使用 python 2.7。在 python 中使用 with_statement 的动机之一是

的代码模式
with threading.Lock(): 
        //User defined function in a new thread 

我不确定我是否理解正确,但我最初的假设是这段代码应该在主线程上获取一个锁,一旦子线程完成,该锁就会被释放。 然而这个脚本

from __future__ import print_function 
import threading 
import time 
import functools 
#import contextlib 
#Thread module for dealing with lower level thread operations.Thread is limited use Threading instead. 
 
def timeit(fn): 
    '''Timeit function like this doesnot work with the thread calls''' 
    def wrapper(*args,**kwargs): 
        start = time.time() 
        fn(*args,**kwargs) 
        end = time.time() 
        threadID = "" 
        print ("Duration for func %s :%d\n"%(fn.__name__ +"_"+ threading.current_thread().name ,end-start)) 
    return wrapper 
 
exitFlag = 0 
 
@timeit 
def print_time(counter,delay): 
    while counter: 
        if exitFlag: 
            thread.exit() 
        time.sleep(delay) 
        print("%s : %s_%d"%(threading.current_thread().name,time.ctime(time.time()),counter)) 
        counter -= 1 
 
class Mythread(threading.Thread): 
    def __init__(self,threadID,name,counter,delay): 
        threading.Thread.__init__(self) 
        self.threadID = threadID 
        self.name = name 
        self.counter = counter 
        self.delay = delay 
 
    def run(self): 
        print("Starting%s\n" % self.name) 
        print_time(self.counter, self.delay) 
        print("Exiting%s\n" % self.name) 
 
 
if __name__ == '__main__': 
    ''' 
    print_time(5, 1) 
     threadLock = threading.Lock() 
     threads = [] 
     thread1 = Mythread(1,"Thread1",5,1) 
     thread2 = Mythread(2,"Thread2",5,2) 
     thread1.start() 
     thread2.start() 
     threads.append(thread1) 
     threads.append(thread2) 
     for t in threads: 
         t.join() 
    ''' 
    thread1 = Mythread(1,"Thread1",5,1) 
    thread2 = Mythread(2,"Thread2",5,2) 
    lock = threading.Lock() 
    with lock: 
        thread1.start() 
        thread2.start() 
 
    print("Exiting main thread ") 

产生以下输出:

StartingThread1 
 
StartingThread2 
 
Exiting main thread  
Thread1 : Sat May 04 02:21:54 2013_5 
Thread1 : Sat May 04 02:21:55 2013_4 
Thread2 : Sat May 04 02:21:55 2013_5 
Thread1 : Sat May 04 02:21:56 2013_3 
Thread1 : Sat May 04 02:21:57 2013_2 
Thread2 : Sat May 04 02:21:57 2013_4 
Thread1 : Sat May 04 02:21:58 2013_1 
Duration for func print_time_Thread1 :5 
 
ExitingThread1 
 
Thread2 : Sat May 04 02:21:59 2013_3 
Thread2 : Sat May 04 02:22:01 2013_2 
Thread2 : Sat May 04 02:22:03 2013_1 
Duration for func print_time_Thread2 :10 
 
ExitingThread2 

请帮助我理解为什么锁定不能像这样与 with_statement 一起工作,或者我是否完全误解了这个概念。我很困惑为什么我直接打印(“退出主线程”),即使通过定义锁也是如此

请您参考如下方法:

您现有的 lock 基本上什么都不做。没有其他线程引用它,因此它不可能导致任何人在任何地方阻塞。它唯一可能做的就是浪费几微秒。所以这个:

lock = threading.Lock() 
with lock: 
    thread1.start() 
    thread2.start() 

... 几乎等同于:

time.sleep(0.001) 
thread1.start() 
thread2.start() 

而且我很确定这不是您想要的。

如果您想强制线程按顺序运行,最简单的方法就是不使用线程。

或者,如果您必须使用线程,只需等待一个完成后再开始下一个:

thread1 = Mythread(1,"Thread1",5,1) 
thread2 = Mythread(2,"Thread2",5,2) 
thread1.start() 
thread1.join() 
thread2.start() 
thread2.join() 

如果你想让线程在没有任何外部帮助的情况下自行序列化,你必须给他们一个他们可以共享的锁。例如:

class Mythread(threading.Thread): 
    def __init__(self,threadID,name,counter,delay,lock): 
        threading.Thread.__init__(self) 
        self.lock = lock 
        # ... 
    def run(self): 
        with self.lock: 
            # ... 

现在,调用它们:

lock = threading.Lock() 
thread1 = Mythread(1,"Thread1",5,1, lock) 
thread2 = Mythread(2,"Thread2",5,2, lock) 
thread1.start() 
thread2.start() 
# ... 
thread1.join() 
thread2.join() 

现在,当每个线程启动时,它都会尝试抢锁。一个会成功,另一个会阻塞,直到第一个完成锁定(通过退出其 with 语句)。


如果您不想序列化线程,您只希望主线程等待所有其他线程完成......为此您需要做的就是join。这正是 join 的用途。无需添加任何其他内容。


如果你真的想要,你可以守护线程并等待一个同步对象。我想不出用锁来做这个的简单方法,但是用 BoundedSemaphore 或 Condition 应该很容易(尽管你必须等待条件两次)。但这是一件非常愚蠢的事情,所以我不确定你为什么要这么做。