Zyc*_*cho 5 python multithreading sync
我必须在Python 2.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;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在做了什么
class CommandSender(threading.Thread)
def __init__(self):
threading.Thread.__init__(self)
self.waiting_list = []
self.running = False
self.is-time_out = False
self.my_lock = threading.Lock()
def run(self):
self.running = True
with self.my_lock:
while len(self.waiting_list) == 0 and self.running:
# Don't know what I have to do here
while len(self.waiting_list) != 0 and self.running:
# Do my stuff
def send_command(self, cmd):
with self.my_lock:
self.waiting_list.append(cmd)
# Notify ?
def is_time_out(self):
with self.my_lock:
return self.is_rime_out
Run Code Online (Sandbox Code Playgroud)
我为每个实例使用一个锁,因为只有一个CommandSender实例
那么如何进行等待/通知过程?我的同步块是否很好用?
谢谢 !
首先,您应该意识到Python的全局解释器锁不允许多个线程同时运行Python代码(尽管线程可以运行例如C代码,例如使用本机代码模块,如果它们适当地释放GIL) 。如果您需要使用 Python 代码来使用多核 CPU,请查看该multiprocessing模块。
现在,直接等价的是类threading.Event。创建一个Event对象,然后使用wait和set。