我必须用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只有一个实例
那么如何执行等待/通知过程呢?我的同步块使用得好吗?在
谢谢!在
首先,您应该知道Python的global interpreter lock不允许多个线程同时运行Python代码(尽管线程可以运行例如C代码,例如,如果适当地释放GIL,则使用本机代码模块)。如果需要使用Python代码使用多核CPU,请查看^{} 模块。在
现在,直接等价的是^{} 类。创建一个}。在
Event
对象,然后使用wait
和{这听起来像是一个简单的生产者-消费者队列。在Java中,您应该考虑使用ConcurrentLinkedQueue。在Python中,线程程序可以使用Queue.Queue类,使用
multiprocessing
的程序可以使用multiprocessing.Queue类。在除非这是家庭作业,并且要求您自己使用特定的锁定机制来实现代码。我知道实现生产者-消费者队列的最简单方法是使用两个或三个信号量:
相关问题 更多 >
编程相关推荐