Headache caused by multi-threading
and Android Open Accessory
.
I need to communicate with a USB Accessory, but I need to do it from 2 threads. One thread generates and sends data the other one reads data.
Why I don't use a single thread? Because there can be 1 or more writes before a read and reads are blocking, so that is not an option.
If using multiple threads, I do run into
I/O Error (No such device)
sooner or later, because I will have a collision between read & write being executed at the same time.Locking will more or less put me back in single-thread situation, so not good.
.available()
method on theinput-stream
returns is not supported, so I cannot check if anything is available before doing a readSince it's not a socket-based stream I cannot set timeout either.
I have tried getting the
FileDescriptor
from theUSBAccessory
and passing toJNI
to handle it there, but after the first read/write the device becomes inaccessible.
Question/Suggestion needed:
What will be a suggested/best-practice approach to this? I do not expect written code, I just need some guidance on how to approach this problem.
To clarify:
The software at the other end might or might NOT respond with any data. There are some so called silent sends were the data sent it's just received but there is no ACK. Since the app I'm working on is only a proxy, I do not have a clear picture if the data will or will not produce an answer. That will require analysis of the data as well, which isn't on the books at the moment.
Thank you.
1 Answers
Answers 1
As you want to do read and write in parallel, writing will always lead to a pause to read if the read is on the same part as write.
May be you can follow similar approach as ConcurrentHashMap
and use different locks for different segments and lock read only if write is on the same segment else allow the read to happen.
This will
- Avoid blocking read during write in most scenarios
- Avoid collision and
- Definitely wont be a single thread approach.
Hope that helps.
0 comments:
Post a Comment