Create a block / wait function?

I am looking for a way to create a function that, like the sockets accept function,
blocks / waits untill a specific variable is set or a specific function is called.
At the moment I am using the very system expensive code:
while(!input);

I need a function that can be called inside a thread procedure to keep the thread from consuming all of the processors power.

Any ideas?



chrille_pAsked:
Who is Participating?
 
itsmeandnobodyelseConnect With a Mentor Commented:
On Windows platform you also may wait on an event rather than on some time elapsed. You may either use WaitForSingleObject or WaitForMultipleObjects:

MSDN says:

The WaitForSingleObject function can wait for the following objects:

Change notification
Console input
Event
Job
Mutex
Process
Semaphore
Thread
Waitable timer

Regards, Alex

0
 
itsmeandnobodyelseCommented:
On Windows platform use

    Sleep(1);    // wait 1 millisecond

in your loop.

Regards, Alex
0
 
itsmeandnobodyelseCommented:
OS/2 you have to use DosSleep, and *NIX it is sleep (as far as i remember).

Regards, Alex
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
chrille_pAuthor Commented:
Im not looking for a function that waits for a couple of seconds.
What I want is a thread-procedure (A) that waits untill function (B) is called...

I could use sleep() in my loop and check a flag every n second, but that would make
the reaction of my function slow. I want it to stop waiting and continue its work
directly when (B) is called.

/Chrille
0
 
chrille_pAuthor Commented:
WaitForSingleObject is perfect.

Thanks!

/Chrille
0
 
grg99Commented:
Depending on the OS, there may be a Sleep() function that is calibrated in milliseconds.

Otherwise you could find some API, any API, that will do a task-switch for you.
On Windows that puts your thread to sleep for about 20-30 milliseconds, a nice ballpark sleep time.

0
 
itsmeandnobodyelseCommented:
>> Im not looking for a function that waits for a couple of seconds.

Ok, but before using
 
    while(!input);

you should have

    while(!input) { sleep(1); }


>> What I want is a thread-procedure (A) that waits untill function (B) is called...

You could use a mutex that gets locked by your main thread, then your thread is waiting on the mutex to be unlocked, what is done at the beginning of function B .

What OS are you working on?

Regards, Alex




 

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.