Windows Threading Wait Method - c++

I'm creating a thread class to encapsulate the windows thread methods. I'm trying to create a method that makes the application wait for the thread to complete before it exits the application. If I use a while loop and boolean flag, it works but obviously it spikes my CPU use and it's just not ideal.
What ways would you use to wait for the completion of a thread? I'm not really looking for code here, just areas to look into.

After you use CreateThread to get a thread handle, pass it into the Win32 API WaitForSingleObject:
WaitForSingleObject(threadhandle, INFINITE);
If you do not use CreateThread (because you use another threading package), or perhaps your thread is always alive...
Then you can still use WaitForSingleObject. Just create an event first with the Win32 API CreateEvent, and wait for the event to be set with WaitForSingleObject. At the end of your thread set the event with SetEvent and you can reset the event with ResetEvent.
Most threading packages though will have their own way to wait for a thread. Like in boost::thread you can use .join() or a boost::condition.

Related

Windows Api Multi-threading Messages

I'm just curious as to to how to implement multi-threading without using a Windows API WaitFor* function that stops the program until the thread has returned. What's the point of using threads if they stop the main application from being resized or moved etc.?
Is there any form of windows messaging with threading, which will allow me to call my thread function and then return, and handle the return values of the thread when it finishes running?
If you want your UI thread to know when a task thread has finished it's task then you could have your task thread post a (custom - WM_USER and above) message to your main window (along with thread id plus the handle). And the window proc of the main window can know that a particular task thread has finished it's task. This way the UI thread does not have to wait actively (using WaitFor*) on the thread(s) object.
You can use MsgWaitForMultipleObjectsEx to wait for the thread to finish and also process messages at the same time.
Have a look at std::thread, boost::thread, just::thread, for multithreading in general for c++.
But about Windows messaging win32 and MFC, the MSDN states explicitely that it is not multithread, it is monothread. ( Undefined behaviour is to be expected if multithreading is used)
For asynchronous message emited in other thread than the main application window thread, you should use ::PostMessage(), that will insert message events in the monothread message pump of the mono threaded window.
WaitForSingleObject can be non-blocking, just pass zero timeout as second parameter:
// Check is thread has been finished
if(::WaitForSingleObject(threadHandle, 0) == WAIT_OBJECT_0)
{
// Process results
...
}
You will need to periodically check this condition, e.g. on timer or after processing any message in message loop.
Or you can use MsgWaitForMultipleObjectsEx. It will unblock and return when some message/input event occured in calling thread message queue.
As other answers mentioned there is another way - using Windows asynchronously posted message to signal that thread has done its work. This way has disadvantage - the working thread must know target window or thread to post message to. This dependency complicates design and raises issues about checking thread/window lifetime. To avoid it message broadcasting (PostMessage(HWND_BROADCAST,...))
can be used, but this is overkill for your case, I don't recommend it.

Callback in user-mode from another process, w/o extra thread

I wonder if anyone familiar with a synchronization mechanism in user-mode, by which an app can register a "callback" function that would be called when another app signals it ... i don't mind the callback to be in an arbitraty thread.
Suppose i'm having lots of "Worker" processes in parallel, And one wants to notify them of a change (no payloaded data needed), by which every process will have to do some internal updates.
The immediate approach to this was to create another thread in each of them, and have an infinite loop that waits for a global event and call the callback function right afterwards. To signal this, one process would only need to signal this global event.
The problem is that i'll have lots of parallel processes in this project, i don't want to add thread*nProcesses to the system just to implement this, even if they're mostly paused.
The current "workaround" i found for this would be to hold my own "dummy" registry key, and every process will "register registery notification callback", when one app wants to notify the others it will just trigger a write to this key... and windows will callback every process which registered to this notification.
Any other ideas?
The nicer solution, which doesn't pollute the registry, would be to use a shared pipe. All workers can connect to the named pipe server, and do an async read. When the server wants to kick the workers, it just writes a byte. This triggers the completion routine of the worker. Basic example
Still, this notification has the same drawback as most other Windows notifications. If all of your worker threads are running worker code, there's no thread on which your notification can arrive - and you didn't create a special thread for that purpose either. The only solution around that is CreateRemoteThread, but that's a very big hammer.
thank you all for the useful ideas,
Eventually, I accidentally came across RegisterWaitForSingleObject which seems to do just that.
I'm still taking in account #MSalters comment about not having enough free worker threads at a given time since i'm assuming this callback mechanism relies on the same callback mechanism most Win32API does

Synchronous vs asynchronous ioctl in worker thread

In a simple MFC application, I need to have a worker thread that constantly poll an ioctl for an event. At first, I attempted to achieve this using non-overlapped ioctl inside a while loop. The way I figured it is that if the ioctl does not complete io request immediately the thread will transfer control or context switch to another thread(the main thread or the MFC message control loop) but instead it locks up the application.
In a second attempt I use an overlapped and the problem is gone. But it seems to me that the two methods are identical in behavior since I use WaitForSingleObject which waits for the event (io request to finish) to trigger.
The basic layout is the following. Note that following code is incomplete and there to show only the construct
Synchronous:
WaitForIo {
do {
DeviceIoControl(hDevice,ioctl_code, ..., NULL);
do something after io request completed
} while(1);
return;
}
Asynchronous:
WaitForIo {
do {
Overlapped ov;
//CreateEvent
DeviceIoControl(hDevice,ioctl_code, ..., &ov);
WaitForSingleObject
do something after io request completed
} while(1);
}
why is the two methods behave differently? Is there something wrong in my logic?
If it locks the thread, it means you need to give back the processor by making it sleep or something like that. WaitForSingleObject does exactly that by default when you call it. I'm not sure about it, but I think that putting null in the DeviceIoControl function made it wait while keeping control over the thread - and so locks the thread.

Suspending and resuming threads in c++

My application has to suspend and resume a different process every few *microsec*s.
It works fine only sometimes it feels like it suspends the process for non-uniforms times.
I use the win API: ResumeThread and SuspendThread.
On the other hand, I tried something a little different.
I suspended the thread as usual with SuspendThread but when I resume it, I do like so:
while (ResumeThread(threadHandle) > 0);
and it works faster and it runs the other process in a uniform pace.
Why does it happen? is it possible that sometimes the thread gets suspended twice and then the ResumeThread command executes?
thanks :)
SuspendThread() call does not suspend a thread instantly. It takes several time to save an execution context, so that ResumeThread() might be called when a thread has not suspended yet. That's why while (ResumeThread(threadHandle) > 0); works. To determine the current thread state you can call NtQueryInformationThread(), but only in NT versions of Windows.
If you have a loop in the secondary thread, you can change your synchronization with a Manual Reset Event. The primary thread should call ResetEvent() to suspend a thread, and SetEvent() to resume. The secondary thread every loop should call WaitForSingleObjectEx().
I followed Damon's suggestion, removed suspend / resume from the code and instead used a synchronization object over which my pool thread waits infinitely after completing the work and the same is signaled by my server thread after allocating work to it.
The only time I have to use suspend now is when I create the thread for the first time and after allocating work to it the thread is resumed from my server thread. The thread created is used in a thread pool over and over again to do some work.
It is working like a charm.
Thank you Damon!
Regards,
Ajay
thats the way de loop look's like
for(i=0;i<num;i++) {
while (ResumeThread(threadHandle) > 0);
ResumeThread(threadHandle)
SuspendThread(threadHandle);
}
SuspendThread takes a few milliseconds so the while loop goes on until thread is suspended, after that, again the thread process SuspendThread function is called, a good way to call GetProcessContext to see EIP

C++ Timers in Unix

We have an API that handles event timers. This API says that it uses OS callbacks to handle timed events (using select(), apparently).
The api claims this order of execution as well:
readable events
writable events
timer events
This works by creating a point to a Timer object, but passing the create function a function callback:
Something along these lines:
Timer* theTimer = Timer::Event::create(timeInterval,&Thisclass::FunctionName);
I was wondering how this worked?
The operating system is handling the timer itself, and when it sees it fired how does it actually invoke the callback? Does the callback run in a seperate thread of execution?
When I put a pthread_self() call inside the callback function (Thisclass::FunctionName) it appears to have the same thread id as the thread where theTimer is created itself! (Very confused by this)
Also: What does that priority list above mean? What is a writable event vs a readable event vs a timer event?
Any explanation of the use of select() in this scenario is also appreciated.
Thanks!
This looks like a simple wrapper around select(2). The class keeps a list of callbacks, I guess separate for read, write, and timer expiration. Then there's something like a dispatch or wait call somewhere there that packs given file descriptors into sets, calculates minimum timeout, and invokes select with these arguments. When select returns, the wrapper probably goes over read set first, invoking read callback, then write set, then looks if any of the timers have expired and invokes those callbacks. This all might happen on the same thread, or on separate threads depending on the implementation of the wrapper.
You should read up on select and poll - they are very handy.
The general term is IO demultiplexing.
A readable event means that data is available for reading on a particular file descriptor without blocking, and a writable event means that you can write to a particular file descriptor without blocking. These are most often used with sockets and pipes. See the select() manual page for details on these.
A timer event means that a previously created timer has expired. If the library is using select() or poll(), the library itself has to keep track of timers since these functions accept a single timeout. The library must calculate the time remaining until the first timer expires, and use that for the timeout parameter. Another approach is to use timer_create(), or an older variant like setitimer() or alarm() to receive notification via a signal.
You can determine which mechanism is being used at the OS layer using a tool like strace (Linux) or truss (Solaris). These tools trace the actual system calls that are being made by the program.
At a guess, the call to create() stores the function pointer somewhere. Then, when the timer goes off, it calls the function you specified via that pointer. But as this is not a Standard C++ function, you should really read the docs or look at the source to find out for sure.
Regarding your other questions, I don't see mention of a priority list, and select() is a sort of general purpose event multiplexer.
Quite likely there's a framework that works with a typical main loop, the driving force of the main loop is the select call.
select allows you to wait for a filedescriptor to become readable or writable (or for an "exception" on the filedeescriptor) or for a timeout to occur. I'd guess the library also allow you to register callbacks for doing async IO, if it's a GUI library it'll get the low primitive GUI events via a file descriptor on unixes.
To implement timer callbacks in such a loop, you just keep a priority queue of timers and process them on select timeouts or filedescriptor events.
The priority means it processes the file i/o before the timers, which in itself takes time, could result in GUI updates eventually resulting in GUI event handlers being run, or other tasks spending time servicing I/O.
The library is more or less doing
for(;;) {
timeout = calculate_min_timeout();
ret = select(...,timeout); //wait for a timeout event or filedescriptor events
if(ret > 0) {
process_readable_descriptors();
process_writable_descriptors();
}
process_timer_queue(); //scan through a timer priority queue and invoke callbacks
}
Because of the fact that the thread id inside the timer callback is the same as the creator thread I think that it is implemented somehow using signals.
When a signal is sent to a thread that thread's state is saved and the signal handler is called which then calls the event call back.
So the handler is called in the creator thread which is interrupted until the signal handler returns.
Maybe another thread waits for all timers using select() and if a timer expires it sends a signal to the thread the expired timer was created in.