Python - 信号量获取可以从特定线程解锁吗?

标签 python multithreading semaphore

我几周前出于学习目的开始使用 Python。 我想知道是否可以解锁从特定线程获取的信号量。或者还有其他工具吗?

import threading, time

sem = threading.Semaphore

def thread1 (threadname):
    #Code to do
    #Condition thread1
    time.sleep(0.001)
    sem.acquire()
    #Code 1
    sem.release

def thread2 (threadname):
    while (thread1.is_alive() == True):
        if #Condition thread1
            sem.acquire()
            #Code 2
            sem.release

我在线程 1 中的条件恰好在 time.sleep 之前(因此线程 2 有时间使用 .acquire 阻塞 thread1)。如果我没有 time.sleep,结果就会不一致。 我现在得到了很好的结果,但我希望线程 2 始终在线程 1 开始“Code1”之前开始其“if”,这样我可以删除该 time.sleep(0.001) 并获得一致结果。

你有什么想法吗?

最佳答案

您要求同步启动行为。为此,您当前使用的信号量不适合。您的编码清楚地表明您不关心哪个进程首先运行。这也是处理事情的标准方式,因此如果您需要一个线程在另一个线程之前,则可能需要一种不同的同步机制。如果我更多地了解您的潜在愿望,我可以告诉您更多信息。

但是,根据您当前的代码,您想要实现的目标将使用第二种机制来完成,在第一个线程尝试获取信号量之前阻塞第一个线程,并且一旦第二个线程进入信号量,就会将其释放它的关键代码块,e。 G。一个threading.Event:

#!/usr/bin/env python3

import threading, time

semaphore = threading.Semaphore()
event = threading.Event()
event.clear() 

def action1():
    print("starting thread1")
    time.sleep(0.1)
    print("waiting in thread1 ...")
    event.wait()
    print("woken up in thread1!")
    print("acquiring in thread1 ...")
    semaphore.acquire()
    print("critical in thread 1")
    semaphore.release()
    print("leaving thread1")

def action2():
    print("starting thread2")
    while (threads[0].is_alive()):
        print("acquiring in thread2 ...")
        semaphore.acquire()
        print("critical in thread 2")
        event.set()
        time.sleep(0.1)
        semaphore.release()
        print("released in thread2")
    print("leaving thread2")

threads = [ threading.Thread(target=action1),
            threading.Thread(target=action2) ]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

但这对我来说似乎很粗鲁并且容易出错。如果您告诉我们您真正想要实现什么,您最初想要解决什么问题,答案可能会得到很大改善。

关于Python - 信号量获取可以从特定线程解锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58972053/

相关文章:

Python 单元测试(使用 SQLAlchemy)不写入/更新数据库?

python - 一些 Python 对象未绑定(bind)到检查点值

python - Django 分组依据

java - 在某些条件下在同步和异步模式之间切换

c++ - 类的std::thread调用方法

c - 信号量锁排队机制?

使用信号量和监视器的 Java Unisex 浴室

python - 如何按继承深度对 Python 类列表进行排序?

c - 如何在 C 中初始化二进制信号量

c++ - C++控制台应用程序未返回