"proper" way to stop a deamon thread from class destructor - multithreading

first of all "proper" because I presume people will tell me that it is a bad practice to launch thread from a class. :)
So I'm wondering what is the best way of stopping a infinite thread in a destructor. Wrapping function that thread calls in try and throwing exception when flag shutdown is set? Just good old int/enum? Good new std::atomic int? Something else?
Now I use:
//in destructor I call terminate member func
void terminate()
{
currentStatus=terminating;
std::cout<<"trying to kill"<<std::endl;
while (currentStatus!=terminated)
std::this_thread::yield();
std::cout<<"MISSION ACOMPLISHED"<<std::endl;
}
And the function that thread runs is:
while (currentStatus==active)
{
//...
}
currentStatus=terminated;
currentStatus is an enum:
enum status{
active,
terminating,
terminated
};

'I presume people will tell me that it is a bad practice to launch thread from a class' - not me, anyway. If you have OO language, where else would you start it from :)
There is an issue with a yield() loop. If the thread calling the destructor has a higher priority than the thread being terminated, your design could livelock forever on a single-processor system. Even on a multi core system, there could be a longish delay. Better to wait on the thread handle or some event that the terminating thread sets as its last action before exit. Not only does that remove the avoidable CPU-looping, it also dodges any cacheing issues with the 'status' emum that might require explicit barriers.
Rgds,
Martin

Related

ReleaseMutex : Object synchronization method was called from an unsynchronized block of code

I have this pretty straightforward piece of code that very rarely throws "System.ApplicationException : Object synchronization method was called from an unsynchronized block of code." when ReleaseMutex() is called.
I logically analyzed the flow of the method and just cannot understand how/why this could happen.
To my understanding, the ownership of mutex is guaranteed in this case:
readonly string mutexKey;
public Logger(string dbServer, string dbName)
{
this.mutexKey = ServiceManagerHelper.GetServiceName(dbServer, dbName);
}
private void Log(LogType type, string message, Exception ex)
{
using (var mutex = new Mutex(false, mutexKey))
{
bool acquiredMutex;
try
{
acquiredMutex = mutex.WaitOne(TimeSpan.FromSeconds(5));
}
catch (AbandonedMutexException)
{
acquiredMutex = true;
}
if (acquiredMutex)
{
try
{
// some application code here
}
finally
{
mutex.ReleaseMutex();
}
}
}
}
catch (AbandonedMutexException)
{
acquiredMutex = true;
}
This is a very serious bug in your code. Catching an AbandonedMutexException is never correct, it is a very serious mishap. Another thread acquired the mutex but terminated without calling ReleaseMutex(). You've irrecoverably lost synchronization and the mutex is no longer usable.
You were sort of lucky by making a mistake and assuming that you acquired the mutex anyway. You didn't. The ReleaseMutex() call will now bomb with the exception you quoted.
You cannot recover from this mishap, other than by terminating the program (the wise choice) or by disabling logging completely so the mutex will never be used again. Make the wise choice by removing the catch clause. Discovering the true source of the problem, that thread that crashed and didn't call ReleaseMutex(), is out of context for this question, there are no hints. You've been ignoring this problem, papered it over by catching AME, you can't ignore it.
In my case, i see the same behavior like Nathan Schubkegel. I use await's, and Thread.CurrentThread.ManagedThreadId gives another value for the "same" thread. I mean, thread was started with ManagedThreadId == 10, and Mutex was owned with this thread id, but later ReleaseMutex() causes ApplicationException with message: "Object synchronization method was called from an unsynchronized block of code", and i see that ManagedThreadId == 11 at this time :) . It seems, await sometimes changes thread id when returns. It seems, that is the reason. Mutex thinks that another thread wants to release it. It's sad, that Mutex documentation does not make ATTENTION on this moment.
So, you CAN NOT use asynchronous operator await between Mutex acquire and release. It's because C# compiler replaces plain operator await by asynchronous callback, and this callback can be made by ANOTHER thread. Usually, it's the same thread, but sometimes it's another thread (from thread pool).
Mutex checks thread. Only thread that acquired Mutex may release it. If you need synchronization without this checking, use Semaphore. SemaphoreSlim has asynchronous method WaitAsync() - it's cool.
This exception is raised when you call ReleaseMutex() from a thread that does not own the mutex. Search // some application code here for code that releases the mutex.
Also reconsider whether you're actually calling ReleaseMutex() from the same thread where you called WaitOne(). Example: I arrived at this post because I was using async/await and my code resumed on a different thread and tried to release a mutex the thread didn't own.

How to close thread winapi

what is the rigth way to close Thread in Winapi, threads don't use common resources.
I am creating threads with CreateThread , but I don't know how to close it correctly in ,because someone suggest to use TerminateThread , others ExitThread , but what is the correct way to close it .
Also where should I call closing function in WM_CLOSE or WM_DESTROY ?
Thx in advance .
The "nicest" way to close a thread in Windows is by "telling" the thread to shutdown via some thread-safe signaling mechanism, then simply letting it reach its demise its own, potentially waiting for it to do so via one of the WaitForXXXX functions if completion detection is needed (which is frequently the case). Something like:
Main thread:
// some global event all threads can reach
ghStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// create the child thread
hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
//
// ... continue other work.
//
// tell thread to stop
SetEvent(ghStopEvent);
// now wait for thread to signal termination
WaitForSingleObject(hThread, INFINITE);
// important. close handles when no longer needed
CloseHandle(hThread);
CloseHandle(ghStopEvent);
Child thread:
DWORD WINAPI ThreadProc(LPVOID pv)
{
// do threaded work
while (WaitForSingleObject(ghStopEvent, 1) == WAIT_TIMEOUT)
{
// do thread busy work
}
return 0;
}
Obviously things can get a lot more complicated once you start putting it in practice. If by "common" resources you mean something like the ghStopEvent in the prior example, it becomes considerably more difficult. Terminating a child thread via TerminateThread is strongly discouraged because there is no logical cleanup performed at all. The warnings specified in the `TerminateThread documentation are self-explanatory, and should be heeded. With great power comes....
Finally, even the called thread invoking ExitThread is not required explicitly by you, and though you can do so, I strongly advise against it in C++ programs. It is called for you once the thread procedure logically returns from the ThreadProc. I prefer the model above simply because it is dead-easy to implement and supports full RAII of C++ object cleanup, which neither ExitThread nor TerminateThread provide. For example, the ExitThread documentation :
...in C++ code, the thread is exited before any destructors can be called
or any other automatic cleanup can be performed. Therefore, in C++
code, you should return from your thread function.
Anyway, start simple. Get a handle on things with super-simple examples, then work your way up from there. There are a ton of multi-threaded examples on the web, Learn from the good ones and challenge yourself to identify the bad ones.
Best of luck.
So you need to figure out what sort of behaviour you need to have.
Following is a simple description of the methods taken from documentation:
"TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
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 if you need your thread to terminate at any cost, call this method.
About ExitThread, this is more graceful. By calling ExitThread, you're telling to windows you're done with that calling thread, so the rest of the code isn't going to get called. It's a bit like calling exit(0).
"ExitThread is the preferred method of exiting a thread. When this function is called (either explicitly or by returning from a thread procedure), the current thread's stack is deallocated, all pending I/O initiated by the thread is canceled, and the thread terminates. If the thread is the last thread in the process when this function is called, the thread's process is also terminated."

ensuring that all threads finish before JVM completely terminates

Let's say I have a SwingWorker object and it's still in its doInBackground() method. If a user calls system.exit(0)...how do I best ensure that the SwingWorker daemon/worker thread completes? I imagine that I have to do this manually. The best idea I have at the moment is to call join() on all outstanding worker threads in/on the same thread that calls System.exit(0)...is this correct?
AND, if using join() is a good idea...should I use it in some sort of while loop in the case that the thread calling join() has spurious activity?
For instance:
//pseudocode
Vector<Thread> threadsThatMustFinishBeforeTerminatingJVM = new Vector<Thread>();
Thread closingThread = new Thread(){
public void run(){
for(Thread t: threadsThatMustFinishBeforeTerminatingJVM){
// closingThread waits for t to finish, (is this *really* safe?)
t.join();
}
System.exit(0);
}
}
closingThread.start();
Is this at all correct?
Take a look here
"The System.exit method forces termination of all threads in the Java virtual machine."
If you call system.exit you're basically saying, "exit now, I don't care what's going on." If you want to shut down cleanly you're going to need to set us some kind of coordination/synchronization between your threads.
If your doInBackground method is still active you could wait until it completes before exiting, some synchronization primitive, shared lock, or some such.
You can add some logic in the done() method of your SwingWorker that would allow an exit.
The better way is probably to query getState() on your SwingWorker. It'll return DONE if the task has completed and if so you can exit, otherwise just wait.

For a Multithreading program, if one thread dies how you can know that ?

For a Multithreading program, if one thread dies how you can know that ?
My idea:
(1) use ps to check LWP but it is manually, not efficient.
(2) set a try-catch in each thread, if it exit non-normally, catch it.
(3) let the dying-thread send a message to std::cout or main thread.
Other better ideas ?
thanks
You could use pthread_cleanup_push(3) at a very early stage in the thread function. The function given to pthread_cleanup_push could set some flag which a "watcher" thread can pick up. pthread_cleanup_push is also honoured by pthread_exit and is not bound to exceptions.
Edit: A second way to do this: Use pthread_key_create(3) with a destructor function and call pthread_setspecific(3) early in the thread function. The destructor function can signal the watching thread it's imminent death.
You could simply use pthread_cleanup_push and pthread_cleanup_pop to execute a cleanup handler on thread exit. This would catch cancellation/pthread_exit events.

System::Threading::Mutex, called from unsynchronized block of code. Unexpected deadlock

In an attempt to rid my GUI of race conditions and deadlocks I have the following function which I call from the c'tor and whenever I need the service which shares my named mutex to provide its input:
void EnvCapt::FireServiceAndOrHold() {
try {
mutTimerSyncEx->ReleaseMutex();
Thread::Sleep(100); //Time enough for the service to complete.
if (!mutTimerSyncEx->WaitOne(3 * int_ms)) {//int_ms = the polling period
//Must've been doubly locked or worse.
mutTimerSyncEx->ReleaseMutex();
FireServiceAndOrHold();
}
} catch (Exception ^ ex) {
//Released unheld mutex. Retake control.
mutTimerSyncEx->WaitOne();
FireServiceAndOrHold();
}
}
This works relatively well but I am calling this before letting the service now I am ready to accept input so it never attempts to wait for me to release the mutex for it. Before I attempt to re-order things I would like to know what is going wrong with the above function. The error I get is:
Object synchronization method was called from an unsynchronized block of code.
Because calling release on a mutex that hasn't been WaitOne'd will throw I catch that, knowing I am free to take ownership of it and continue. But I am wrong. It hangs forever on the WaitOne() statement. I know what the other process is doing all this time because it is trapped in my second debugger window. It is not touching the mutex.
UPDATE
I've attempted the reordering I first suggested, this seemed good but now I find that the mutex is only sort of Global, despite having a Global\name.
It is shared because when my GUI c'tor's it firstInstance is false, hence I attempt to take control of it.
It is not shared because when the GUI calls WaitOne() on it the GUI blocks indefinitely. Whereas the service dances straight through its call to WaitOne() without a care in the world.
I just had an idea what might be going wrong for you there:
Hint: you cannot release a mutex on behalf of the other process! The other process will have to release the mutex if it holds it:
Process 1: Process 2:
============ =============
WaitOne (locks the mutex)
// do work WaitOne (awaits the mutex)
// do more work
// done
ReleaseMutex ------> WaitOne returns from the wait _with
the mutex locked_

Resources