Skip to main content
 首页 » 编程设计

python之如何同步python线程

2024年10月17日8bjzhanghao

我想同步两个线程:一个追加,另一个从列表中弹出:

import threading 
 
 
class Pop(threading.Thread): 
    def __init__(self, name, alist): 
        threading.Thread.__init__(self) 
        self.alist = alist 
        self.name = name 
 
    def run(self): 
        print "Starting " + self.name 
        self.pop_from_alist(self.alist) 
        print "Exiting " + self.name 
 
    def pop_from_alist(self, alist): 
        alist.pop(0) 
 
 
def main(): 
    alist = [1, 2] 
    # Create new thread 
    thread = Pop("Pop thread", alist) 
    for x in range(2): 
        alist.append(alist[-1]+1) 
    thread.start() 
    print "Exiting Main Thread" 
    print alist 
main() 

我该怎么做,我应该使用 Lock 还是使用 join 方法? 找不到任何适合初学者的同步教程

请您参考如下方法:

两个线程需要共享同一个锁。这样他们就可以知道另一个线程何时锁定了它。您需要在主线程中定义锁并在初始化时将其传递给您的线程:

# Create a lock 
lock = threading.Lock() 
 
# Create new threads 
thread1 = Append("Append thread", alist, lock) 
thread2 = Pop("Pop thread", alist, lock) 
 
# Start new Threads 
thread1.start() 
thread2.start() 

在线程中,您可以像以前那样处理它,但跳过锁创建:

class Append(threading.Thread): 
    def __init__(self, name, alist, lock): 
        threading.Thread.__init__(self) 
        self.alist = alist 
        self.name = name 
        self.lock = lock 
 
def append_to_list(self, alist, counter): 
    while counter: 
        with self.lock: 
            alist.append(alist[-1]+1) 
            counter -= 1