Skip to content

Commit

Permalink
Reduced CPU usage in MidiInputDevice.
Browse files Browse the repository at this point in the history
  • Loading branch information
kshoji committed Mar 24, 2014
1 parent a0b0626 commit 3cfa61d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
25 changes: 20 additions & 5 deletions MIDIDriver/src/jp/kshoji/driver/midi/device/MidiInputDevice.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public MidiInputDevice(UsbDevice usbDevice, UsbDeviceConnection usbDeviceConnect
public void stop() {
usbDeviceConnection.releaseInterface(usbInterface);

waiterThread.suspendFlag = false;
resume();
waiterThread.stopFlag = true;

// blocks while the thread will stop
Expand All @@ -76,14 +76,19 @@ public void stop() {
* Suspends event listening
*/
public void suspend() {
waiterThread.suspendFlag = true;
synchronized (waiterThread.suspendSignal) {
waiterThread.suspendFlag = true;
}
}

/**
* Resumes event listening
*/
public void resume() {
waiterThread.suspendFlag = false;
synchronized (waiterThread.suspendSignal) {
waiterThread.suspendFlag = false;
waiterThread.suspendSignal.notifyAll();
}
}

/**
Expand Down Expand Up @@ -115,6 +120,7 @@ public UsbEndpoint getUsbEndpoint() {
*/
final class WaiterThread extends Thread {
volatile boolean stopFlag;
final Object suspendSignal = new Object();
volatile boolean suspendFlag;

/**
Expand Down Expand Up @@ -147,8 +153,17 @@ public void run() {
while (!stopFlag) {
int length = deviceConnection.bulkTransfer(usbEndpoint, bulkReadBuffer, maxPacketSize, 0);
if (length > 0) {
if (suspendFlag) {
continue;
synchronized (suspendSignal) {
if (suspendFlag) {
try {
// check the deviceConnection to ignore events while suspending.
// Note: Events received within last sleeping(100msec) will be sent to the eventListener.
suspendSignal.wait(100);
} catch (InterruptedException e) {
// ignore exception
}
continue;
}
}

System.arraycopy(bulkReadBuffer, 0, readBuffer, readBufferSize, length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public MidiOutputDevice(UsbDevice usbDevice, UsbDeviceConnection usbDeviceConnec
public void stop() {
usbDeviceConnection.releaseInterface(usbInterface);

waiterThread.suspendFlag = false;
resume();
waiterThread.stopFlag = true;
waiterThread.interrupt();

Expand Down Expand Up @@ -177,7 +177,7 @@ public void run() {
if (suspendFlag) {
try {
// sleep until interrupted
Thread.sleep(500);
sleep(500);
} catch (InterruptedException e) {
// interrupted: event queued, or stopFlag/suspendFlag changed.
}
Expand Down Expand Up @@ -226,7 +226,7 @@ public void run() {
if (queueSize == 0 && !interrupted()) {
try {
// sleep until interrupted
Thread.sleep(500);
sleep(500);
} catch (InterruptedException e) {
// interrupted: event queued, or stopFlag changed.
}
Expand Down

0 comments on commit 3cfa61d

Please sign in to comment.