2017-01-03 69 views
2

我想两个线程同步:一个追加,另外空间PoPing从列表:如何同步python线程?

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() 

我怎样才能做到这一点,我应该用锁或使用的连接方法? 无法找到任何初学者的同步教程

+0

请查看[Python队列](https://docs.python.org/2/library/queue.html)。让我知道你是否需要一个完整的答案! –

回答

2

两个线程需要共享相同的锁。这样他们就会知道其他线程何时锁定它。你需要在你的主线程来定义锁并将它传递给你的线程上初始化:

# 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 
+0

有没有必要使用lock.acquire和release()? – Alexey

+1

@AlexeyUstinnikov:'带'进入/退出序列在进入时获取锁定,并在退出时释放它。这是一个非常好的方法来执行操作,同时保持锁定,因为它可以确保即使在例外或键盘中断时锁定也被释放。 – torek