Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Timeouts in a thread?

Status
Not open for further replies.

danielmashman

Programmer
Sep 12, 2011
4
0
0
NZ
Hi All,

I have a borland c++ builder application where I am lauching a thread to manage USB HID communications with an external device. I want to wait a specified amount of time at a point within this thread for the device to be attached. Is there an easy way of setting up a timeout to do this? I could have a for loop with a counter and use Sleep() routine but not sure if this is the best way of doing it.

I apologize in advance for the lack of information but not really sure what extra info to provide. Please ask if neccessary.
 
If you want to suspend unconditionally, the Sleep function (w/o any loop counters) is the best way to go (it's exactly what this function is intendened for).

For more advanced HID programming stuff look at
 
I have not tried anything like this myself before, but have you tried creating a timer object and then using WaitForEvent? Like I said, I have not done this so I do not have any sample code, but I would look at Windows System calls of CreateWaitableTimer, SetWaitableTimer and OpenWaitableTimer, as well as WaitForSingleObject. Alternatively, you could investigate CreateEvent, and set the timeout parameter of the WaitForSingleObject. Just a couple of approaches to try.
 
Thanks for the responses. Here's a more detailed description of what I am trying to do:
The particular part in the code is attempting to put the USB HID device into a boot loader mode by sending a USB command. Once the device receives this command I know it will disconnect and reconnect from the USB as it enters the bootloader mode. I have a rough idea of how long this will take (something in the order of 300ms). I have registered for device events in my application so I know when a USB device is attached/detached so what I want is a loop that continuously poles a flag for the device to be attached for a maximum time of (say 500ms).

I think the easiest way would be to do something like this:

Code:
for(timout = 50; ((timeout > 0) && !DeviceAttached); timeout--)
    sleep(10);    //suspend for 10ms

if(!DeviceAttached)
    return -1;    //error

//check this is the correct device (PID, VID)

Not sure how long do get the thread to sleep for between checking the DeviceAttached flag though. I think 10ms should be fine.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top