Skip to content

Commit 3dedf95

Browse files
authored
Merge pull request #279 from ShimmerResearch/DEV-895
DEV-895 Stop per-device reader threads busy-spinning when idle
2 parents f95ff52 + 8e9e63f commit 3dedf95

5 files changed

Lines changed: 519 additions & 78 deletions

File tree

‎ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java‎

Lines changed: 76 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -584,71 +584,94 @@ public ShimmerBluetooth(String userAssignedName, double samplingRate, int enable
584584
}
585585

586586
public class ProcessingThread extends Thread {
587-
public boolean stop = false;
587+
public volatile boolean stop = false;
588588
int count=0;
589589
public void run() {
590-
while (!stop) {
591-
if(!mABQPacketByeArray.isEmpty()){
590+
while (!stop && !Thread.currentThread().isInterrupted()) {
591+
RawBytePacketWithPCTimeStamp rbp = null;
592+
try {
593+
// Blocks (with a timeout) instead of busy-spinning on isEmpty() while idle.
594+
// The timeout ensures the stop flag is still checked periodically.
595+
rbp = mABQPacketByeArray.poll(100, TimeUnit.MILLISECONDS);
596+
} catch (InterruptedException e) {
597+
Thread.currentThread().interrupt();
598+
}
599+
if(rbp!=null){
592600
count++;
593601
if(count%1000==0){
594602
consolePrintLn("Queue Size: " + mABQPacketByeArray.size());
595603
printLogDataForDebugging("Queue Size: " + mABQPacketByeArray.size() + "\n");
596604
}
597-
RawBytePacketWithPCTimeStamp rbp = mABQPacketByeArray.remove();
598605
// buildAndSendMsg(rbp.mDataArray, FW_TYPE_BT, false, rbp.mSystemTimeStamp);
599606
buildAndSendMsg(rbp.mDataArray, COMMUNICATION_TYPE.BLUETOOTH, false, rbp.mSystemTimeStamp);
600607
}
601-
}
602-
}
603-
}
608+
}
609+
}
610+
}
604611

605612
//region --------- BLUETOOH STACK ---------
606613

607614
public class IOThread extends Thread {
608615
protected byte[] byteBuffer = {0};
609-
public boolean stop = false;
616+
public volatile boolean stop = false;
610617

611618
public void run() {
612-
while(!stop) {
619+
while(!stop && !Thread.currentThread().isInterrupted()) {
620+
boolean didWork = false;
613621
//In-Shimmer Test here
614622
if(InShimmerTest) {
615623
if (bytesAvailableToBeRead()) {
616-
byte[] data = readBytes(availableBytes());
617-
if (data!=null) {
618-
if (data.length>0) {
619-
if (mTestByteListener != null) {
620-
mTestByteListener.eventNewBytesReceived(data);
621-
}
624+
didWork = true;
625+
byte[] data = readBytes(availableBytes());
626+
if (data!=null) {
627+
if (data.length>0) {
628+
if (mTestByteListener != null) {
629+
mTestByteListener.eventNewBytesReceived(data);
630+
}
631+
}
622632
}
623633
}
624-
}
625634
}
626635
else {
627636
if (mDummyRead) {
628637
performDummyRead();
638+
didWork = true;
629639
}
630-
640+
631641
// Process Instruction on stack. is an instruction running? if not proceed
632642
if(!isInstructionStackLock()){
633-
processNextInstruction();
643+
if(processNextInstruction()){
644+
didWork = true;
645+
}
634646
}
635-
647+
636648
if(mIsStreaming){
637649
processWhileStreaming();
650+
didWork = true;
638651
}
639652
else if(bytesAvailableToBeRead()){
653+
didWork = true;
640654
if(mWaitForAck) {
641655
processNotStreamingWaitForAck();
642-
}
656+
}
643657
else if(mWaitForResponse) {
644658
processNotStreamingWaitForResp();
645-
}
646-
659+
}
660+
647661
processBytesAvailableAndInstreamSupported();
648-
662+
663+
}
664+
}
665+
666+
if(!didWork){
667+
// Nothing useful happened this iteration (idle, not streaming, no pending
668+
// instructions/bytes) - avoid busy-spinning and pegging a CPU core.
669+
try {
670+
Thread.sleep(2);
671+
} catch (InterruptedException e) {
672+
Thread.currentThread().interrupt();
649673
}
650674
}
651-
652675
}
653676
}
654677

@@ -681,10 +704,16 @@ private void performDummyRead() {
681704
mDummyReadStarted = false;
682705
}
683706

684-
private void processNextInstruction() {
707+
/**
708+
* @return true if an instruction was found and processed (i.e. useful work was done),
709+
* or if this call already idle-paced the loop with its own threadSleep(50) below -
710+
* in that case reporting true here stops run()'s outer idle-sleep from stacking an
711+
* additional wait on top of this one.
712+
*/
713+
private boolean processNextInstruction() {
685714
// check instruction stack, are there any other instructions left to be executed?
686715
//checkAndRemoveFirstInstructionIfNull();
687-
716+
688717
byte[] insBytes = getInstruction();
689718
if (insBytes!=null){
690719
mCurrentCommand=insBytes[0];
@@ -761,14 +790,32 @@ else if((mCurrentCommand==GET_FW_VERSION_COMMAND)
761790

762791

763792
mTransactionCompleted=false;
793+
return true;
764794
} else {
795+
// getInstruction() returned null here - either the instruction stack is
796+
// genuinely empty, or its leading entry was a null placeholder that
797+
// getInstruction() just removed (a real instruction may still be next in
798+
// the list and will be picked up on the following iteration). Either way,
799+
// if there's also nothing else to do this iteration, wait here rather than
800+
// busy-spinning.
765801
if (!mIsStreaming && !bytesAvailableToBeRead()){
766-
threadSleep(50);
802+
// Report "did work" (true) so the caller's own idle sleep in run()
803+
// doesn't stack an extra wait on top of this one.
804+
// Not threadSleep(): that helper swallows InterruptedException without
805+
// restoring the interrupt flag, which would defeat run()'s
806+
// !Thread.currentThread().isInterrupted() loop-exit check.
807+
try {
808+
Thread.sleep(50);
809+
} catch (InterruptedException e) {
810+
Thread.currentThread().interrupt();
811+
}
812+
return true;
767813
}
814+
return false;
768815
}
769816
}
770-
771-
/** Process ACK from a GET or SET command while not streaming */
817+
818+
/** Process ACK from a GET or SET command while not streaming */
772819
private void processNotStreamingWaitForAck() {
773820
//JC TEST:: IMPORTANT TO REMOVE // This is to simulate packet loss
774821
/*

‎ShimmerDriver/src/main/java/com/shimmerresearch/comms/radioProtocol/LiteProtocol.java‎

Lines changed: 93 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -253,49 +253,108 @@ private void startIoThread() {
253253
}
254254

255255
private void stopIoThread() {
256-
if(mIOThread!=null){
257-
mIOThread.stop=true;
258-
mIOThread = null;
256+
// Snapshot the field: a concurrent teardown may null mIOThread between the
257+
// null check and the interrupt/join/isAlive calls below.
258+
IOThread ioThread = mIOThread;
259+
if(ioThread!=null){
260+
ioThread.stop=true;
261+
// Bounded wait for the thread to actually exit its loop before dropping the
262+
// reference. Guard against the self-join case: killConnection() can reach here
263+
// synchronously from within IOThread.run()'s catch block (error-driven teardown),
264+
// and a thread joining itself would just burn the full timeout.
265+
if(Thread.currentThread() != ioThread){
266+
// Interrupt before joining: run() now exits promptly on
267+
// Thread.currentThread().isInterrupted(), and any idle Thread.sleep()/
268+
// queue poll() it's waiting in will wake immediately - making shutdown
269+
// faster and more deterministic than waiting out the bounded join first.
270+
ioThread.interrupt();
271+
try {
272+
ioThread.join(2000);
273+
} catch (InterruptedException e) {
274+
Thread.currentThread().interrupt();
275+
}
276+
if (ioThread.isAlive()) {
277+
// Still not terminated after the interrupt + bounded join - most likely
278+
// blocked in a non-interruptible native serial read. Just warn; a second
279+
// interrupt() here wouldn't unblock it either.
280+
printLogDataForDebugging("Warning: IOThread did not terminate within join timeout; it may be blocked in a non-interruptible read");
281+
}
282+
}
283+
// Only clear the field if it still refers to the thread we stopped, so a
284+
// newly started IOThread is not clobbered.
285+
if (mIOThread == ioThread) {
286+
mIOThread = null;
287+
}
259288
}
260289
}
261290

262291

263292
public class IOThread extends Thread {
264293
byte[] byteBuffer = {0};
265-
public boolean stop = false;
294+
public volatile boolean stop = false;
266295

267-
public synchronized void run() {
268-
while (!stop) {
296+
/*
297+
* Deliberately NOT synchronized: Thread.join() locks this same Thread
298+
* instance, so a synchronized run() would block external stopIoThread()
299+
* callers on monitor entry (with no timeout) until the loop exits.
300+
*/
301+
public void run() {
302+
while (!stop && !Thread.currentThread().isInterrupted()) {
303+
boolean didWork = false;
269304
try {
270305
// Process Instruction on stack. is an instruction running? if not proceed
271306
if(!isInstructionStackLock()){
272-
processNextInstruction();
307+
if(processNextInstruction()){
308+
didWork = true;
309+
}
273310
}
274-
311+
275312
if(isStreaming()){
276313
processWhileStreaming();
314+
didWork = true;
277315
}
278316
else if(bytesAvailableToBeRead()){
317+
didWork = true;
279318
if(mWaitForAck) {
280319
processNotStreamingWaitForAck();
281-
}
320+
}
282321
else if(mWaitForResponse) {
283322
processNotStreamingWaitForResp();
284-
}
285-
323+
}
324+
286325
processBytesAvailableAndInstreamSupported();
287326
}
288327
} catch (ShimmerException dE) {
289328
// stop=true;
290-
291-
killConnection(dE);
329+
330+
// DEV-895: once stop is set, an error here is the teardown interrupt surfacing
331+
// (e.g. as ERR_WRITING_DATA from txBytes), not a real link failure.
332+
if(!stop){
333+
killConnection(dE);
334+
}
292335
// e.printStackTrace();
293336
//TODO send event up the ladder
294337
}
295-
}
296-
}
297-
298-
private void processNextInstruction() throws ShimmerException {
338+
339+
if(!didWork){
340+
// Nothing useful happened this iteration (idle, not streaming, no pending
341+
// instructions/bytes) - avoid busy-spinning and pegging a CPU core.
342+
try {
343+
Thread.sleep(2);
344+
} catch (InterruptedException e) {
345+
Thread.currentThread().interrupt();
346+
}
347+
}
348+
}
349+
}
350+
351+
/**
352+
* @return true if an instruction was found and processed (i.e. useful work was done),
353+
* or if this call already idle-paced the loop with its own threadSleep(50) below -
354+
* in that case reporting true here stops run()'s outer idle-sleep from stacking an
355+
* additional wait on top of this one.
356+
*/
357+
private boolean processNextInstruction() throws ShimmerException {
299358
// check instruction stack, are there any other instructions left to be executed?
300359
if(!getListofInstructions().isEmpty()) {
301360
if(getListofInstructions().get(0)==null) {
@@ -387,16 +446,29 @@ else if((mCurrentCommand==InstructionsGet.GET_FW_VERSION_COMMAND_VALUE)
387446
}
388447
}*/
389448
}
390-
391-
449+
450+
392451
mTransactionCompleted=false;
452+
return true;
393453
}
394-
}
454+
}
395455
else {
396456
if (!isStreaming() && !bytesAvailableToBeRead()){
397-
threadSleep(50);
457+
// No instruction pending and nothing else to do - wait here rather than
458+
// busy-spinning. Report "did work" (true) so the caller's own idle sleep
459+
// in run() doesn't stack an extra wait on top of this one.
460+
// Not threadSleep(): that helper swallows InterruptedException without
461+
// restoring the interrupt flag, which would defeat run()'s
462+
// !Thread.currentThread().isInterrupted() loop-exit check.
463+
try {
464+
Thread.sleep(50);
465+
} catch (InterruptedException e) {
466+
Thread.currentThread().interrupt();
467+
}
468+
return true;
398469
}
399470
}
471+
return false;
400472
}
401473

402474
private void processWhileStreaming() throws ShimmerException {

0 commit comments

Comments
 (0)