gpt4 book ai didi

python - 如何同步python线程?

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:18 25 4
gpt4 key购买 nike

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

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

关于python - 如何同步python线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41441900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com