Loading screen animation using threads - c++

I have made a game, it is written in C++ and directX.
When the user chooses which mission to play the screen goes blank for some time while it load in all the resources. So the user knows the game has not crashed I want to make a loading screen with an animation.
My question is this:
If one thread (the main one) crashes do all threads of that process crash?
Can you destroy a thread from the thread that created it or does the thread have to terminate itself?
I am new to multithreading and have not used it before. Many people say it makes programs unnecessarily complex so is it worth making my program multithreaded just for a loading screen or is there another way of doing it?

If one thread (the main one) crashes do all threads of that process crash?
If the main thread crashes (i.e. the UI thread) obviously the application crashes. If any worker thread crashes, you will get an exception which you can choose to ignore.
Can you destroy a thread from the thread that created it or does the thread have to terminate itself?
Normally the thread itself should terminate itself (i.e. finish execution). Obviously you can signal any secondary thread to stop from the main thread.
I am new to multithreading and have not used it before. Many people say it makes programs unnecessarily complex so is it worth making my program multithreaded just for a loading screen or is there another way of doing it?
You'll have to learn multitasking if you're serious about programming so better now than never.

If one thread (the main one) crashes do all threads of that process crash?
If by 'crash' you mean that an unhandled exception is propagated to the operating system - Yes.
Can you destroy a thread from the thread that created it or does the thread have to terminate itself?
There's TerminateThread, but it's use is not recommended. Better notify the thread that it should terminate and leave the actual cleanup to the thread.
I am new to multithreading and have not used it before. Many people say it makes programs unnecessarily complex so is it worth making my program multithreaded just for a loading screen or is there another way of doing it?
A loading screen is actually a good example of multithreading. I wouldn't, however, create an extra thread to render your loading screen but rather use multiple threads to stream in your resources. Rendering should be done by one thread (that's generally recommended for all DirectX versions).

Related

c++ child threads terminating on main() parent thread exit?

VS2013, C++
I just release dll application. One of dll app function run thread by _beginthread.
In normal software flow I use mutex and control threads. Before unregister dll from main application I wait for thread terminating and close handlers.
However there is one case that main application could close without release resources in correct way I mean without waiting for child thread terminating and without close of handlers.
Is there any risk if main application force exit? Is there any risk if I run application and threads again after exit?
Is there any risk for OS? Are all threads terminating after main exit?
I know that it is "dirty" solution but for some reason I can’t change that.
Thank you in advance for advices.
According to Raymond Chen - in Windows systems - if the main thread terminates, your application hangs while all your threads end. This means, no your solution will not work, your thread will freeze your application in the closing state. Also even if your thread would be forcefully terminated on exit, it would not be uninitialized, and - since we are talking about MFC threads here - it would cause your application to leak resources, so pretty please don't do that!
Is there any risk if main application force exit?
Yes! Since thread can have started consistence-sensitive processes.
Is there any risk if I run application and threads again after exit?
Yes! May be previous shutdown crushed the data structure and now you cannot even load data correctly
Is there any risk for OS?
It depends on your business. May be you create a soft for disk-optimization and you are moving clusters while emergency shutdown?
Are all threads terminating after main exit?
Yes! You need foreseen special "join" code that waits accomplishment of threads.
I would say, the behavior is undefined. Too many things may happen, when the application is terminated without having the chance to clean up.
This SO question may give some ideas.
This MS article describes TerminateThread function and also lists some implication of unexpectedly terminating the threads (which is probably happened on calling exit):
If the target thread owns a critical section, the critical section
will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be
inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users
of the DLL.
So looks like there is a risk even for the OS
kernel32 state for the thread's process could be inconsistent

Terminating Qt worker thread during program shutdown

I use Qt 4.8.6, MS Visual Studio 2008, Windows 7. I've created a GUI program. It contains main GUI thread and worker thread (I have not made QThread subclass, by the way), which makes synchronous calls to 3rd party DLL functions. These functions are rather slow. QTcpServer instance is also under worker thread. My worker class contains QTcpServer and DLL wrapper methods.
I know that quit() is preferred over terminate(), but I don't wanna wait for a minute (because of slow DLL functions) during program shutdown. When I try to terminate() worker thread, I notice warnings about stopping QTcpServer from another thread. What is a correct way of process shutdown?
QThread::quit tells the thread's event loop to exit. After calling it the thread will get finished as soon as the control returns to the event loop of the thread
You may also force a thread to terminate right now via QThread::terminate(), but this is a very bad practice, because it may terminate the thread at an undefined position in its code, which means you may end up with resources never getting freed up and other nasty stuff. So use this only if you really can't get around it.
So i think the right approach is to first tell the thread to quit normally and if something goes wrong and takes much time and you have no way to wait for it, then terminate it:
QThread * th = myWorkerObject->thread();
th->quit();
th->wait(5000); // Wait for some seconds to quit
if(th->isRunning()) // Something took time more than usual, I have to terminate it
th->terminate();
You should always try to avoid killing threads from the outside by force and instead ask them nicely to finish what they're doing. This usually means that the thread checks regularly if it should terminate itself and the outside world tells it to terminate when needed (by setting a flag, signaling an event or whatever is appropriate for the situation at hand).
When a thread is asked to terminate itself, it finishes up what it's doing and exists cleanly. The application waits for the thread to terminate and then exits.
You say that in your case the thread takes a long time to finish. You can take this into consideration and still terminate the thread "the nice way" (for example you can hide the application window and give the impression that the app has exited, even if the process takes a little more time until it finally terminates; or you can show some form of progress indication to the user telling him that the application is shutting down).
Unless there is an overriding reason to do so, you should not attempt to terminate threads with user code at process-termination.
If there is no such reason, just call your OS process termination syscall, eg. ExitProcess(0). The OS can, and will will stop all process threads in any state before releasing all process resources. User code cannot do that, and should not try to terminate threads, or signal them to self-terminate, unless absolutely necessary.
Attempting to 'clean up' with user code sounds 'nice', (aparrently), but is an expensive luxury that you will pay for with extra code, extra testing and extra maintenance.
That is, if your customers don't stop buying your app because they get pissed off with it taking so long to shut down.
The OS is very good at stopping threads and cleaning up. It's had endless thousands of hours of testing during development and decades of life in the wild where problems with process termination would have become aparrent and got fixed. You will not even get close to that with your flags, events etc. as you struggle to stop threads running on another core without the benefit of an interprocessor driver.
There are surely times when you will have to resort to user code to stop threads. If you need to stop them before process termination, or you need to close some DB connection, flush some file at shutdown, deal with interprocess comms or the like issues, then you will have to resort to some of the approaches already suggested in other answers.
If not, don't try to duplicate OS functionality in the name of 'niceness'. Just ask it to terminate your process. You can get your warm, fuzzy feeling when your app shuts down immedately while other developers are still struggling to implement 'Shutdown' progress bars or trying to explain to customers why they have 15 zombie apps still running.

Threads creating process in infinite loop

In my application a thread runs while(1){} in it so thread terminates when my app is terminated by user.
Is it safe to do like this? I am using while(1){} because my app continuously monitors devices on system.
After some time I am getting "(R6016) not enough space for thread data" on ffmpeg.
I read this but did not get solution of my problem:
http://support.microsoft.com/kb/126709
Thread description:
Thread uses ffmpeg and handle utility (http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx). within while(1){} loop.
ffmpeg and handle is running through QProcess which I am deleting after process ends.
while(1){} loop waits for 5 seconds using
msleep(5000).
This is not safe.
Change while (1) to while (!stopCondition) and have stopCondition change to TRUE when exiting. The main thread should wait for all other thread to finish before exiting.
Note: stopCondition is defined as volatile int stopCondition.
When the main thread exists, a cleanup process starts:
- global destructors are called (C++).
- C runtime library starts to shut down, releasing all memory allocated with malloc, unloading dynamic libraries and other resources.
A thread that depends on the C runtime being functional will crash or if it runs code from a shared/dynamic libray. If that thread was doing something important like writing to a file, the file will be corrupt. Maybe in your case things are not so bad, but seeing an application crash doesn't looks good to say the least.
This is not the full story, but I think it makes my point.

MFC: accessing GUI from another thread?

So generally only the main thread should access the GUI in a MFC application.
However is that a law or just recommended? If I make sure, via critical sections, that only one thread accesses a certain object in the GUI, is it ok then? Or is it a problem if the MAIN thread accesses one part of the GUI while another thread access one. Even if those 2 objects don't affect each other?
The reason I ask is because this simplifies my rewrite of the application a lot if I can access the GUI from another thread.
Don't do it. You'll live in a world of ASSERTs and weird behaviour if you do. The GUI works through a system of Windows messages which are 'pumped' on the main thread. If you start modifying the UI in another thread you'll have situations where your operation causes other UI messages, which will be handled by the main thread potentially at the same time you're still trying to access the UI on another thread.
MFC programming is hard enough without trying to handle this sort of thing. Instead use PostMessage to put the UI related handling onto the main thread.
I used to think its almost forbidden to access GUI from a worker thread in MFC and is a recipe for disaster. But recently I learned this is not that hard rule if you know what you are doing, you can use worker threads to access GUI. In the Win32 Multithreaded Book the provides an example of a 'self animated control' which is completely drawn in a worker thread.
If I remember correctly the author pretty much said the same thing you said, if you critical sections at the right places you can make accessing GUI thread safe. The reason MFC doesn't do it by itself is for performance reasons.

How to avoid hung processing in C++ through multithreading

In my code the main loop looks like the following
while ( (data = foo()) != NULL ) {
// do processing on data here
}
where foo() is written in C (it fetches the next frame in a video stream, using libavcodec, if you're curious).
My problem is that due to reasons too complicated to go in here, sometimes foo() hangs, which stops the whole program. What I want to do is to detect this condition, i.e. foo() is taking more than N seconds and if this is so take action.
I thought of creating a separate thread to run foo() to implement this by I haven't done any multithreaded programming before. Here's what I want to do:
Main thread creates a child thread and which calls foo()
When foo() is done, the child thread returns
Main thread processes data returned by foo()
If the child takes more than a specified number of time an action is taken by the main thread.
Steps 1-4 are repeated as long as foo() doesn't return null, which signals the end.
How do I go about doing this? Do I need three threads (main, to run foo() and for timing)?
Thanks!
This is exceedingly difficult to do well. The problem is what you're going to do when foo hangs. Nearly the only thing you can do at that point is abort the program (not just the thread) and start over -- killing the thread and attempting to re-start it might work, but it's dangerous at best. The OS will clean up resources when you kill a process, but not when you kill a single thread. It's essentially impossible to figure out what resources belong exclusively to that thread, and what might be shared with some other thread in the process.
That being the case, perhaps you could move the hanging-prone part to a separate process instead, and kill/restart that process when/if it hangs? You'd then send the data to the parent process via some normal form of IPC (e.g., a pipe). In this case, you could have two threads in the parent (processor and watchdog), or (if available) you could do some sort of asynchronous read with time out, and kill the child when/if the read times out (using only one thread).
How do I go about doing this?
You don't. The hard thing is that there is no reliable way to stop a thread - assuming the hang is in libavcodec, interrupting/killing a thread stuck in code you do not have control over leads to more problems than it solves(it might just be memory and file handle leaks if you're not too unlucky). The thread has to stop itself - but that's not an option if you're stuck inside libavcodec.
Many threading implementation doesn't let you kill threads either - though you might request that the thread cancels , if it's stuck in a infinite loop, it'll never cancel though as the cancel requests are processed only at certain boundary points in the OS or low level library calls.
To work around a buggy library like that in a reliable way, you need process isolation. What you do is create a separate program out of your foo() function, execute that and communicated with it using its stdin/stout streams - or some other form of IPC. Talking to an external program, you have various options for doing I/O with timeouts, and can kill the program when you determin it's hanging.
On Linux you can use pthread_timedjoin_np to make this happen with two threads really easily.
I think you can do this with two threads and use the sleep() command in the main thread for the timing part as long as you don't need to do other work there.
You'd probably be better off just fixing what ever is hanging your application.