Reputation: 3957
I am writing a wrapper around the C++ API of a programme, which needs to connect to a network. I want my own Connect() function to wait for 2 seconds or less, and continue if no connection is established. What I was thinking of is simply using Sleep(...)
and checking again, but this doesn't work:
class MyWrapperClass
{
IClient* client;
bool MyWrapperClass::Connect()
{
client->Connect();
int i = 0;
while (i++ < 20 && !client->IsConnected())
Sleep(100); /* Sleep for 0.1 s to give client time to connect (DOESN'T HAPPEN) */
return client->IsConnected();
}
}
I am assuming that this fails (i.e. no connection is established) because the thread as a whole stops, including the IClient::Connect()
method. I have no access to this method, so I cannot verify whether this starts any other threads or anything.
Is there a better way to have a function wait for a short while without blocking anything?
Edit:
To complicate matters consider the following: the programme has to be compiled with /clr
as the API demands this (so std::thread
cannot be used) AND IClient
cannot be an unmanaged class (i.e. IClient^ client = gcnew IClient()
is not legal), as the class contains unmanaged stuff. Neither is in my power to alter, as it is demanded by the API.
Upvotes: 1
Views: 740
Reputation: 230
As others pointed out you can't wait without blocking. Blocking IS the entire point of waiting.
I would look carefully af IClient and read any documentation to ensure there is no function that lets you do this asynchronously.
If you have no luck, then you are left with doing a loop with sleep in you code. If you can use c++11 then Chris gave a good suggetion. Otherwise you are left with whatever your OS gives you. On a POSIX system (unix) you could try usleep() or nanosleep() to give you shorter sleep than sleep() see http://linux.die.net/man/3/usleep.
Upvotes: 1
Reputation: 23916
If you want to connect without switching to another thread you can use system-specific options for that. For example setsockopt() for SO_RCVTIMEO option before connect will help you on linux. You can try to find a way to pass a preconfigured socket to the library in question.
Upvotes: 0