Understanding TCriticalSection and Synchronize - multithreading

I would like to confirm here if I understood correctly how TCriticalSection and Synchronize operate.
As far as I know right now Synchronize uses SendMessage (update: or at least used it in older VCL versions as mentioned in couple of comments below) which suspends currently executing thread (as well as any other thread) unlike PostMessage which doesn't and then executes required function (from main thread). In a way SendMessage "stops" multithreading when executing.
But I am not sure about TCriticalSection. Let's say for example I create something like this:
// Global variables somewhere in my code any thread can access
boost::scoped_ptr<TCriticalSection> ProtectMyVarAndCallFnction(new TCriticalSection);
int MyVariable1;
void CallMyFunctionThatAlsoModifiesMoreStuff() { /* do even more here */ };
// Thread code within one of the threads
try {
ProtectMyVarAndCallFnction->Acquire();
MyVariable1++;
CallMyFunctionThatAlsoModifiesMoreStuff();
}
__finally {
ProtectMyVarAndCallFnction->Release();
}
Now, my question is - how the critical section "knows" that I am protecting MyVariable1 in this case as well as whatever the called function may modify?
If I understood it correctly - it doesn't - and it is my responsibility to correctly call Acquire() in any thread wants to change MyVariable1 or call this function (or do any of the two). In other words I think of TCriticalSection as user-defined block which defines whatever logically I assigned to it. It may be a set of variables or any particular function as long as I call Acquire() within all of the threads that might write to this block or use this function. For example "DiskOp" may be my name of TCriticalSection that writes on disk, "Internet" may be the name of TCriticalSection that calls functions that retrieve some data from the Internet. Did I get it correctly?
Also, within this context, does TCriticalSection therefore always needs to be a global kind of variable?

SendMessage suspends currently executing thread (as well as any other thread).
No, that is incorrect. SendMessage does not suspend anything. SendMessage merely delivers a message synchronously. The function does not return until the message has been delivered. That is, the window proc of the target window has been executed. And because the window proc is always called on the thread that owns the window, this means that the calling thread may need to be blocked to wait until the window's owning thread is ready to execute the window proc. It most definitely doesn't suspend all threads in the process.
How does the critical section know that I am protecting MyVariable1?
It doesn't. It's entirely up to you to make sure that all uses of MyVariable1 that need protection, are given protection. A critical section is a form of mutex. A mutex ensures that only one thread of execution can hold the mutex any any instant in time.
As I call Acquire() within all of the threads that might write to this block or use this function.
That's not really it either. The "within all of the threads" is a mis-think. You need to be thinking about "at all sections of code that use the variable".
Does a critical section therefore always need to be a global kind of variable?
No, a critical section can be a global variable. But it need not be.

Related

How can we know we are inside a spinlock?

I have a function which is called by multiple functions. Some functions call it with spinlock held and some without any lock. How can I know if my function is called with spinlock held?
I have a big piece of code written some time back. It has some functions which are called with and without locks from different code paths. The functions allocate skbs with GFP_KERNEL flag only considering the cases without locks. It is causing issues when called with spin_lock(). I need to handle both the cases to avoid sleeping inside a spin_lock.
How can I know if my function is called with spinlock held?
You cannot, not directly. You would need to set a flag in some structure yourself that indicates whether you hold the lock or not.
You are better off creating 2 functions. One that you call if you hold the lock, one that you call if you don't hold the lock.
//b->lck must be taken
void foo_unlocked(struct bar *b)
{
//do your thing, assume relevant lock is held
}
//b->lck must not be taken
void foo(struct bar *b)
{
spin_lock(b->lck);
foo_unlocked(b);
spin_unlock(b->lck);
}
I need to check only preemption disabled or irqs disabled. Based on that I can allocate memory with GFP_KERNEL or GFP_ATOMIC. Hence I don't need to rely on when spin_lock or another lock. Using in_atomic() and irqs_disabled() functions, I can achieve it. Thanks

Mutex not Releasing at all

I would like to have one instance of an .exe running and am using mutex as follows in app::InitInstance()
hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, _T("app.0"));
if (!hMutex)
hMutex = CreateMutex(0, 0, _T("app.0"));
In app::ExitInstance() I have
int iii = ReleaseMutex(hMutex);
where hMutex is a global variable: HANDLE hMutex;
This works and only limits the app to one instance. However, upon closing I get the following message using GetLastError(): "Attempt to release mutex not owned by caller."
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411(v=vs.85).aspx
Remarks
The ReleaseMutex function fails if the calling thread does not own the
mutex object.
A thread obtains ownership of a mutex either by creating it with the
bInitialOwner parameter set to TRUE or by specifying its handle in a
call to one of the wait functions. When the thread no longer needs to
own the mutex object, it calls the ReleaseMutex function so that
another thread can acquire ownership.
A thread can specify a mutex that it already owns in a call to one of
the wait functions without blocking its execution. This prevents a
thread from deadlocking itself while waiting for a mutex that it
already owns. However, to release its ownership, the thread must call
ReleaseMutex one time for each time that it obtained ownership (either
through CreateMutex or a wait function).
And
HANDLE WINAPI CreateMutex(
_In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
_In_ BOOL bInitialOwner,
_In_opt_ LPCTSTR lpName
);
Ownership or release of mutex is not required in this case, since you aren't doing any resource protection. You may, however, issue a CloseHandle on it - which will decrease the reference count, and when last handle is closed, the mutex object will be destroyed. You, don't need to call it either, as OS will do it for you (and would maintain reference counting mechanism also).
You may, however, need to close it as soon as possible, when second instance is running (possibility displaying a dialog box). In this case, just before displaying the dialog (that "Another instance is running"), you must close it. If you don't do, consider a scenario:
Application is normally started.
Another instance (by mistake) is launched, the new process detects it and displays a dialog box (without closing the handle).
You close the actual application opened in step 1 (but you don't close the dialog shown on (2)).
Now, you attempt to launch application - it will say that application is already running - which in fact, is not running (only a dialog is displayed).

Why pass parameters through thread function?

When I create a new thread in a program... in it's thread handle function, why do I pass variables that I want that thread to use through the thread function prototype as parameters (as a void pointer)? Since threads share the same memory segments (except for stack) as the main program, shouldn't I be able to just use the variables directly instead of passing parameters from main program to new thread?
Well, yes, you could use the variables directly. Maybe. Assuming that they aren't changed by some other thread before your thread starts running.
Also, a big part of passing parameters to functions (including thread functions) is to limit the amount of information the called function has to know about the outside world. If you pass the thread function everything it needs in order to do its work, then you can change the rest of the program with relative impunity and the thread will still continue to work. If, however, you force the thread to know that there is a global list of strings called MyStringList, then you can't change that global list without also affecting the thread.
Information hiding. Encapsulation. Separation of concerns. Etc.
You cannot pass parameters to a thread function in any kind of normal register/stack manner because thread functions are not called by the creating thread - they are given execution directly by the underlying OS and the API's that do this copy a fixed number of parameters, (usually only one void pointer), to the new and different stack of the new thread.
As Jim says, failure to understand this mechanism often results in disaster. There are numnerous questions on SO where the vars that devs. hope would be used by a new thread are RAII'd away before the new thread even starts.

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."

Multithreading (pthreads)

I'm working on a project where I need to make a program run on multiple threads. However, I'm running into a bit of an issue.
In my program, I have an accessory function called 'func_call'.
If I use this in my code:
func_call((void*) &my_pixels);
The program runs fine.
However, if I try to create a thread, and then run the function on that, the program runs into a segmentation fault.
pthread_t thread;
pthread_create (&thread, NULL, (void*)&func_call, (void*) &my_pixels);
I've included pthread.h in my program. Any ideas what might be wrong?
You are not handling data in a thread safe manner:
the thread copies data from the thread argument, which is a pointer to the main thread's my_pixels variable; the main thread may exit, making my_pixles invalid.
the thread uses scene, main thread calls free_scene() on it, which I imagine makes it invalid
the thread calls printf(), the main thread closes stdout (kind of unusual itself)
the thread updates the picture array, the main thread accesses picture to output data from it
It looks like you should just wait for the thread to finish its work after creating it - call pthread_join() to do that.
For a single thread, that would seem to be pointless (you've just turned a multi-threaded program into a single threaded program). But on the basis of code that's commented out, it looks like you're planning to start up several threads that work on chunks of the data. So, when you get to the point of trying that again, make sure you join all the threads you start. As long as the threads don't modify the same data, it'll work. Note that you'll need to use separate my_pixels instances for each thread (make an array of them, just like you did with pthreads), or some threads will likely get parameters that are intended for a different thread.
Without knowing what func_call does, it is difficult to give you an answer. Nevertheless, here are few possibilities
Does func_call use some sort of a global state - check if that is initialized properly from within the thread. The order of execution of threads is not always the same for every execution
Not knowing your operating system (AIX /Linux/Solaris etc) it is difficult to answer this, but please check your compilation options
Please provide the signal trapped and atleast a few lines of the stack-trace - for all the threads. One thing you can check for yourself is to print the threads' stack-track (using threads/thread or pthread and thread current <x> based on the debugger) and and if there is a common data that is being accessed. It is most likely that the segfault occurred when two threads were trying to read off the other's (uncommitted) change
Hope that helps.
Edit:
After checking your code, I think the problem is the global picture array. You seem to be modifying that in the thread function without any guards. You loop using px and py and all the threads will have the same px and py and will try to write into the picture array at the same time. Please try to modify your code to prevent multiple threads from stepping on each other's data modifications.
Is func_call a function, or a function pointer? If it's a function pointer, there is your problem: you took the address of a function pointer and then cast it.
People are guessing because you've provided only a fraction of the program, which mentions names like func_call with no declaration in scope.
Your compiler must be giving you diagnostics about this program, because you're passing a (void *) expression to a function pointer parameter.
Define your thread function in a way that is compatible with pthread_create, and then just call it without any casts.

Resources