Python的等效Java函数wait(),notify(),synchronized

2024-04-27 23:10:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须用Python2.7编写一个类,但我遇到了一些问题。 我有java背景,最近才学会了python

如果我必须用java编写,下面是我要写的

public class CommandSender extends Thread {
    private boolean isTimeOut;
    private boolean running;
    private ArrayList<Command> waitingList;

    public CommandSender() {
        running = false;
        waitingList = new LinkedList<Command>();
        isTimeOut = false;
    }

    public void run() {
        running = true;
        while (running) {
            synchronized (this) {
                 while (waitingList.isEmpty() && running) {
                     try {
                         wait();
                     } catch (InterruptedException ie) {
                         ie.printStackTrace();
                     }
                  }
                  while (!waitingList.isEmpty() && running) {
                      currentCmd = waitingList.remove(0);
                      // doSomething(currentCmd)
                  }
             }
        }
    }

    public synchronized void sendCommand(Command cmd) {
        waitingList.add(cmd);
        notify();
    }

    public synchronized boolean isTimeOut() {
        return isTimeOut;
    }
}

我现在要做的事

^{pr2}$

我为每个实例使用一个锁,因为CommandSender只有一个实例

那么如何执行等待/通知过程呢?我的同步块使用得好吗?在

谢谢!在


Tags: falsejavaprivatepublicrunningcommandieboolean
2条回答

首先,您应该知道Python的global interpreter lock不允许多个线程同时运行Python代码(尽管线程可以运行例如C代码,例如,如果适当地释放GIL,则使用本机代码模块)。如果需要使用Python代码使用多核CPU,请查看^{}模块。在

现在,直接等价的是^{}类。创建一个Event对象,然后使用wait和{}。在

这听起来像是一个简单的生产者-消费者队列。在Java中,您应该考虑使用ConcurrentLinkedQueue。在Python中,线程程序可以使用Queue.Queue类,使用multiprocessing的程序可以使用multiprocessing.Queue类。在

除非这是家庭作业,并且要求您自己使用特定的锁定机制来实现代码。我知道实现生产者-消费者队列的最简单方法是使用两个或三个信号量:

  • 一个信号量,用于计算队列中的元素数。最初是零。在
  • 一个信号量,用于计算队列中元素的限制/最大数量,并以此最大数量初始化。如果不需要有限的队列,这是可选的。在
  • 一个信号量、互斥或关键部分,用于共享对内部队列/链接列表的访问。在Python中,线程程序不需要这样做,因为GIL允许您向列表中添加元素,而无需同步线程。在

相关问题 更多 >