如何同步python线程?

时间:2017-01-03 10:56:32

标签: python multithreading

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

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或使用连接方法,我该怎么做? 无法为初学者找到任何同步教程

1 个答案:

答案 0 :(得分: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
相关问题