Python 线程和信号量

6 投票
1 回答
7778 浏览
提问于 2025-04-17 19:33

我有一个Python类,叫做AClass,还有一个叫MyThread的类,它是从Thread类扩展出来的。在这个AClass里,我创建了两个MyThread类的对象,并且我还有一个信号量(semaphore),我把它作为参数传给MyThread类的构造函数。我的问题是,如果我在一个MyThread对象里修改了信号量,另一个MyThread对象会看到这个变化吗?比如:

class AClasss:

     def function: 
          semafor = threading.Semaphore(value=maxconnections)
          thread1 = Mythread(semafor)
          thread2 = Mythread(semafor)
          thread1.start()
          thread1.join()
          thread2.start()
          thread2.join()

 class MyThread(Thread):
     def __init__(self,semaphore):
         self.semaphore = semaphore
     def run():
        semaphore.acquire()
        "Do something here" 
        semaphore.release()

那么,thread1会看到thread2对信号量的修改吗?反之亦然?

1 个回答

7

信号量的作用就是帮助你安全地同步同时运行的程序。

要记住,在Python中,线程如果不释放全局解释器锁(GIL),其实是不能真正实现并发的(比如进行输入输出操作、调用库等等)。如果你想要实现并发,可能需要考虑使用 multiprocessing 这个库。

撰写回答