I have to write a class in Python 2.7 and I have some problems. I come from a java background and learned python quite recently
Here is what I would write if i have to do in 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;
}
}
What i have do for the moment
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
I use one lock per instance because there is only one instance of CommandSender
So How to do the wait/notify process ? And are my synchronised block well used ?
Thanks !
First of all, you should be aware of Python's global interpreter lock will not allow more than one thread to run Python code at the same time (though threads can run e.g. C code, for example using native code modules if they release the GIL appropriately). If you need to make use of a multicore CPU using Python code, check out the multiprocessing
module.
Now, the direct equivalent is the threading.Event
class. Create an Event
object, then use wait
and set
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With