6

我有一个 python 类,我们称之为 AClass 和另一个扩展 Thread 的 MyThread。在那个 AClass 中,我创建了 MyThread 类的 2 个对象,并且我还有一个信号量,我将它作为参数提供给 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 对信号量所做的更改,反之亦然?

4

1 回答 1

7

这就是信号量的目的,它们允许您安全地同步并发进程。

请记住,除非您释放 GIL(执行 IO、调用库等),否则Python 中的线程不会真正让您获得并发性。如果这就是你想要的,你可能需要考虑multiprocessing图书馆。

于 2013-03-18T19:54:09.690 回答