How to handle a PostMessageThread message in std::thread? - c++

Somewhere in my main thread I am calling PostThreadMessage(). But I don't know how to handle it in the std::thread I have sent it to.
I am trying to handle it in std::thread like this:
while(true) {
if(GetMessage(&msg, NULL, 0, 0)) {
// Doing appropriate stuff after receiving the message.
}
}
And I am sending the message from the main thread like this:
PostThreadMessage(thread.native_handle(), WM_CUSTOM_MESSAGE, 0, 0);
I don't know if I am supposed to receive the message as I did in my thread.
All I want to know is, how to check whether the "worker thread" is receiving the message I am sending it.

What std::thread::native_handle() returns is implementation-defined (per [thread.req.native] in the C++ standard). There is no guarantee that it even returns a thread ID that PostThreadMessage() wants.
For instance, MSVC's implementation of std::thread uses CreateThread() internally, where native_handle() returns a Win32 HANDLE. You would have to use GetThreadId() to get the thread ID from that handle.
Other implementations of std::thread might not use CreateThread() at all. For instance, they could use the pthreads library instead, where native_handle() would return a pthread_t handle, which is not compatible with Win32 APIs.
A safer way to approach this issue is to not use native_handle() at all. Call GetCurrentThreadId() inside of your thread function itself, saving the result to a variable that you can then use with PostThreadMessage() when needed, for example:
struct threadInfo
{
DWORD id;
std::condition_variable hasId;
};
void threadFunc(threadInfo &info)
{
info.id = GetCurrentThreadId();
info.hasId.notify_one();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
// Doing appropriate stuff after receiving the message.
}
}
...
threadInfo info;
std::thread t(threadFunc, std::ref(info));
info.hasId.wait();
...
PostThreadMessage(info.id, WM_CUSTOM_MESSAGE, 0, 0);

Related

c++ implementing semaphore on my own

let's pretend there are no libraries that provide semaphores for C++. I wrote this:
#include <vector>
#include <Windows.h>
class Semaphore {
HANDLE mutexS; // provides mutex in semaphore rutines
std::vector<HANDLE> queue; // provides FIFO queue for blocked threads
int value; // semaphore's value
public:
Semaphore(int init=1);
~Semaphore();
void wait();
void signal();
};
Semaphore::Semaphore(int init) {
value = init;
queue = std::vector<HANDLE>();
mutexS = CreateMutex(0,0,0);
}
Semaphore::~Semaphore() {
CloseHandle(mutexS);
}
void Semaphore::signal() {
WaitForSingleObject(mutexS, INFINITE);
if (++value <= 0) {
HANDLE someOldThread = queue.front();
ResumeThread(someOldThread);
queue.erase(queue.begin());
CloseHandle(someOldThread);
}
ReleaseMutex(mutexS);
}
I would like to know why this implementation of wait() doesn't work:
void Semaphore::wait() {
WaitForSingleObject(mutexS, INFINITE);
if (--value < 0) {
HANDLE thisThread = GetCurrentThread();
queue.push_back(thisThread);
ReleaseMutex(mutexS);
SuspendThread(thisThread );
}
else
ReleaseMutex(mutexS);
}
And this one works:
void Semaphore::wait() {
WaitForSingleObject(mutexS, INFINITE);
if (--value < 0) {
HANDLE thisThread = GetCurrentThread();
HANDLE alsoThisThread;
DuplicateHandle(GetCurrentProcess(), thisThread, GetCurrentProcess(), &alsoThisThread, 0, 0, DUPLICATE_SAME_ACCESS);
queue.push_back(alsoThisThread);
ReleaseMutex(mutexS);
SuspendThread(alsoThisThread);
}
else
ReleaseMutex(mutexS);
}
What exactly happens in each case? I've been banging my head over it for a lot of time now. The first implementation of wait, which doesn't work, makes my program block (well, it probably blocks some thread forever). The 2nd implementation works like a charm. What gives ? Why do I need to duplicate thread handles and block the duplicate ?
MSDN helps a lot here ;)
GetCurrentThread returns a pseudo-handle which is a constant for "the current thread":
A pseudo handle is a special constant that is interpreted as the current thread handle.
So when you push it in the queue, you are always pushing a constant that says "the current thread", which is obviously not what you want.
To get a real handle, you have to use DuplicateHandle
If hSourceHandle is a pseudo handle returned by GetCurrentProcess or GetCurrentThread, DuplicateHandle converts it to a real handle to a process or thread, respectively.
A final note: I suppose you are implementing this as a "test" right? Because there are several potential problems.. A very good learning exercise would be to dig them out. But you should not use this in production code.
Out of curiosity: if you want to experiment a little more, the "canonical" way of implementing semaphore with mutexes is to use two mutexes: see here
MSDN documentation for GetCurrentThread has the answer (accents are mine):
The return value is a pseudo handle for the current thread.
A pseudo handle is a special constant that is interpreted as the current thread handle. The calling thread can use this handle to specify itself whenever a thread handle is required.
...
The function cannot be used by one thread to create a handle that can be used by other threads to refer to the first thread. The handle is always interpreted as referring to the thread that is using it. A thread can create a "real" handle to itself that can be used by other threads, or inherited by other processes, by specifying the pseudo handle as the source handle in a call to the DuplicateHandle function.

Multithreading with _beginthread and CreateThread

I try to write a Multithreading WIN32 Application in C++, but due to i get difficulties.
One of the Window Procedure creates a Thread, which manages the output of this window. If this Window Procedure receives a message (from the other Window Procedures), it should transmit it to their Thread. At the beginning i worked with the _beginthread(...) function, what doesn't work.
Then i tried it with the CreateThread(...) function, and it worked? What did i do wrong?
(My English isn't so good, i hope you understand my problem)
Code with CreateThread(...):
DWORD thHalloHandle; // global
HWND hwndHallo; // Hwnd of WndProc4
...
LRESULT APIENTRY WndProc4 (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static PARAMS params ;
switch (message)
{
case WM_CREATE: {
params.hwnd = hwnd ;
params.cyChar = HIWORD (GetDialogBaseUnits ()) ;
CreateThread(NULL, 0, thHallo, &params, 0, &thHalloHandle);
return 0 ;
}
...
case WM_SPACE: {
PostThreadMessage(thHalloHandle, WM_SPACE, 0, 0);
return 0;
}
...
}
Code with _beginthread(...):
...
case WM_CREATE: {
params.hwnd = hwnd ;
params.cyChar = HIWORD (GetDialogBaseUnits ()) ;
thHalloHandle = (DWORD)_beginthread (thHallo, 0, &params) ;
return 0;
}
...
case WM_SPACE: {
PostThreadMessage(thHalloHandle, WM_SPACE, 0, 0);
return 0;
}
...
thHallo for CreateThread:
DWORD WINAPI thHallo(void *pvoid)
{
static TCHAR *szMessage[] = { TEXT(...), ...};
// Some Declaration
pparams = (PPARAMS) pvoid;
while(!pparams->bKill)
{
MsgReturn = GetMessage(&msg, NULL, 0, 0);
hdc = GetDC(pparams->hwnd);
if(MsgReturn)
{
switch(msg.message)
{
// case....
}
}
}
return 0;
}
thHallo for _beginthread(...):
void thHallo(void *pvoid)
{
...
// The Same like for CreateThread
...
_endthread();
}
The _beginthread/ex() function is proving to be radically difficult to eliminate. It was necessary back in the previous century, VS6 was the last Visual Studio version that required it. It was a band-aid to allow the CRT to allocate thread-local state for internal CRT variables. Like the ones used for strtok() and gmtime(), CRT functions that maintain internal state. That state must be stored separately for each thread so that the use of, say, strtok() in one thread doesn't screw up the use of strtok() in another thread. It must be stored in thread-local state. _beginthread/ex() ensures that this state is allocated and cleaned-up again.
That has been worked on, necessarily so when Windows 2000 introduced the thread-pool. There is no possible way to get that internal CRT state initialized when your code gets called by a thread-pool thread. Quite an effort btw, the hardest problem they had to solve was to ensure that the thread-local state is automatically getting cleaned-up again when the thread stops running. Many a program has died on that going wrong, Apple's QuickTime is a particularly nasty source of these crashes.
So forget that _beginthread() ever existed, using CreateThread() is fine.
There's a serious problem with your use of PostThreadMessage(). You are used the wrong argument in your _beginthread() code which is why it didn't work. But there are bigger problems with it. The message that is posted can only ever be retrieved in your message loop. Which works fine, until it is no longer your message loop that is dispatching messages. That happens in many cases in a GUI app. Simple examples are using MessageBox(), DialogBox() or the user resizing the window. Modal code that works by Windows itself pumping the message loop.
A big problem is the message loop in that code knows beans about the messages you posted. They just fall in the bit-bucket and disappear without trace. The DispatchMessage() call inside that modal loop fails, the message you posted has a NULL window handle.
You must fix this by using PostMessage() instead. Which requires a window handle. You can use any window handle, the handle of your main window is a decent choice. Better yet, you can create a dedicated window, one that just isn't visible, with its own WndProc() that just handles these inter-thread messages. A very common choice. DispatchMessage() can now no longer fail, solves your bug as well.
Your call to CreateThread puts the thread ID into thHalloHandle. The call to _beginthread puts the thread handle into thHalloHandle.
Now, the thread ID is not the same as the thread handle. When you call PostThreadMessage you do need to supply a thread ID. You only do that for the CreateThread variant which I believe explains the problem.
Your code lacks error checking. Had you checked for errors on the call to PostThreadMessage you would have found that PostThreadMessage returned FALSE. Had you then gone on to call GetLastError that would have returned ERROR_INVALID_THREAD_ID. I do urge you to include proper error checking.
In order to address this you must first be more clear on the difference between thread ID and thread handle. You should give thHalloHandle a different name: thHalloThreadId perhaps. If you wish to use _beginthread you will have to call GetThreadId, passing the thread handle, to obtain the thread ID. Alternatively, use _beginthreadex which yields the thread ID, or indeed CreateThread.
Your problem is that you need a TID (Thread Identifier) to use PostThreadMessage.
_beginthread doesn't return a TID, it return a Thread Handle.
Solution is to use the GetThreadId function.
HANDLE hThread = (HANDLE)_beginthread (thHallo, 0, &params) ;
thHalloHandle = GetThreadId( hThread );
Better Code (see the documentation here)
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, thHallo, &params, 0, &thHalloHandle ) ;

Windows: WaitForSingleObject crashes when thread returns 0

I am having a strange behavior: WaitForSingleObject seems to crash when I return 0 from my thread, but if I call "ExitThread(0)" then it does not.
void waitForThread(DWORD &threadId)
{
HANDLE hThread = OpenThread(SYNCHRONIZE,
FALSE,
threadId);
if (hThread == NULL) return;
WaitForSingleObject(hThread, INFINITE); // Crashes here (not even returning)
CloseHandle(hThread);
}
According to the documentation:
ExitThread is the preferred method of exiting a thread in C code. However, 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.
This does not make sense to me. I would think that "return 0" in my function with the signature:
DWORD WINAPI foo(LPVOID arg);
would be fine. For completeness, the thread is created using CreateThread, as such:
DWORD threadId;
HANDLE pth = CreateThread(NULL, // Default security attributes
0, // Default stack size
foo, // Thread name
arg, // Argument to thread
0, // Default creation flag
&threadId); // Returns thread ID
Does anyone know why the return statement would crash "WaitForSingleObject" please? I have put print statement before and after WaitForSingleObject, and one when the thread exists, and the behavior I see is: "Before WaitForSingleObject", "Thread finishes", Crash. Does anyone understand this behavior please?

c++ winapi threads

These days I'm trying to learn more things about threads in windows. I thought about making this practical application:
Let's say there are several threads started when a button "Start" is pressed. Assume these threads are intensive (they keep running / have always something to work on).
This app would also have a "Stop" button. When this button is pressed all the threads should close in a nice way: free resources and abandon work and return the state they were before the "Start" button was pressed.
Another request of the app is that the functions runned by the threads shouldn't contain any instruction checking if the "Stop" button was pressed. The function running in the thread shouldn't care about the stop button.
Language: C++
OS: Windows
Problems:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
How should I construct the wrapper function so that I can stop the thread properly?
( without using TerminateThread or some other functions )
What if the programmer allocates some memory dynamically? How can I free it before closing
the thread?( note that when I press "Stop button" the thread is still processing data)
I though about overloading the new operator or just imposing the usage of a predefined
function to be used when allocating memory dynamically. This, however, means
that the programmer who uses this api is constrained and it's not what I want.
Thank you
Edit: Skeleton to describe the functionality I'd like to achieve.
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
( free memory allocated dynamically etc )
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);
One solution is to have some kind of signal that tells the threads to stop working. Often this can be a global boolean variable that is normally false but when set to true it tells the threads to stop. As for the cleaning up, do it when the threads main loop is done before returning from the thread.
I.e. something like this:
volatile bool gStopThreads = false; // Defaults to false, threads should not stop
void thread_function()
{
while (!gStopThreads)
{
// Do some stuff
}
// All processing done, clean up after my self here
}
As for the cleaning up bit, if you keep the data inside a struct or a class, you can forcibly kill them from outside the threads and just either delete the instances if you allocated them dynamically or let the system handle it if created e.g. on the stack or as global objects. Of course, all data your thread allocates (including files, sockets etc.) must be placed in this structure or class.
A way of keeping the stopping functionality in the wrapper, is to have the actual main loop in the wrapper, together with the check for the stop-signal. Then in the main loop just call a doStuff-like function that does the actual processing. However, if it contains operations that might take time, you end up with the first problem again.
See my answer to this similar question:
How do I guarantee fast shutdown of my win32 app?
Basically, you can use QueueUserAPC to queue a proc which throws an exception. The exception should bubble all the way up to a 'catch' in your thread proc.
As long as any libraries you're using are reasonably exception-aware and use RAII, this works remarkably well. I haven't successfully got this working with boost::threads however, as it's doesn't put suspended threads into an alertable wait state, so QueueUserAPC can't wake them.
If you don't want the "programmer" of the function that the thread will execute deal with the "stop" event, make the thread execute a function of "you" that deals with the "stop" event and when that event isn't signaled executes the "programmer" function...
In other words the "while(!event)" will be in a function that calls the "job" function.
Code Sample.
typedef void (*JobFunction)(LPVOID params); // The prototype of the function to execute inside the thread
struct structFunctionParams
{
int iCounter;
structFunctionParams()
{
iCounter = 0;
}
};
struct structJobParams
{
bool bStop;
JobFunction pFunction;
LPVOID pFunctionParams;
structJobParams()
{
bStop = false;
pFunction = NULL;
pFunctionParams = NULL;
}
};
DWORD WINAPI ThreadProcessJob(IN LPVOID pParams)
{
structJobParams* pJobParams = (structJobParams*)pParams;
while(!pJobParams->bStop)
{
// Execute the "programmer" function
pJobParams->pFunction(pJobParams->pFunctionParams);
}
return 0;
}
void ThreadFunction(LPVOID pParams)
{
// Do Something....
((structFunctionParams*)pParams)->iCounter ++;
}
int _tmain(int argc, _TCHAR* argv[])
{
structFunctionParams stFunctionParams;
structJobParams stJobParams;
stJobParams.pFunction = &ThreadFunction;
stJobParams.pFunctionParams = &stFunctionParams;
DWORD dwIdThread = 0;
HANDLE hThread = CreateThread(
NULL,
0,
ThreadProcessJob,
(LPVOID) &stJobParams, 0, &dwIdThread);
if(hThread)
{
// Give it 5 seconds to work
Sleep(5000);
stJobParams.bStop = true; // Signal to Stop
WaitForSingleObject(hThread, INFINITE); // Wait to finish
CloseHandle(hThread);
}
}

Defining function inside function call

I had an idea to save time involving creating a temporary function to use as an argument to a function that needs it. The reason I'm after this behaviour is to do things in a new thread in an easy manner (using Win32 API) without having to define all kinds of functions I'll use.
Here's an example:
void msg (const string & message) {
MessageBox (0, message.c_str(), "Message", 0);
}
This will produce a message box, but your program is halted until it closes. The solution is to create a thread for the message box that runs concurrently with the main thread.
void msg (const string & message) {
CreateThread (0, 0,
(LPTHREAD_START_ROUTINE)({MessageBox (0, message.c_str(), "Message", 0);}),
0, 0, 0);
}
In this case, LPTHREAD_START_ROUTINE is defined as
typedef DWORD (*LPTHREAD_START_ROUTINE)(LPVOID param);
Since I have multiple functions wanting another thread for a purpose like that, putting the function in the call to CreateThread seems to be working well.
But say I wanted to use that LPVOID param. I'd like to know how standard this method is, and where I can find out how to use it for more advanced techniques. Also, I know using it in a function that will store it for later use (eg. a message loop function where you can add messages to handle and a corresponding function to call) is a bad idea as the function is temporary and would not be able to be called when needed. Is there really any use beyond things like threads where it's annoying to make one line functions elsewhere in order to use it?
It's called a "lambda". They are very useful for many purposes beyond this and are in the C++11 Standard. You can find them in the latest GCC and MSVC. However, MSVC's current implementation does not permit conversion to a function pointer, as the Standard did not specify such a conversion at that time. VC11 will implement this conversion. This code is Standard-conforming C++11:
void msg (const string & message) {
CreateThread (0, 0,
[](LPVOID* param) { MessageBox (0, message.c_str(), "Message", 0); },
0, 0, 0);
}
There was another way in times lambdas were not the standard - you could define function-local class and define the inner function within that class. Something like:
void msg(const string &message)
{
struct message_box
{
static DWORD WINAPI display(LPVOID param)
{
/// do the action
return 0;
}
};
::CreateThread(0, 0,
&message_box::display,
0, 0, 0);
}
Now lets consider your question. You wanted to pass the message text in STL's std::string. Since it occupies dynamic memory which can be freed by your initial thread, the new thread, running in parallel, must have guarantee, that the message text will still be available to it. This can be done by copying (which would work with lambda's by-value capture - [=] introducer) or sharing a reference (via reference counting, let'd say). Lets consider copying:
void msg(const string &message)
{
struct message_box
{
static DWORD WINAPI display(void *param)
{
MessageBox(0, ((string *)param)->c_str(), "Message", 0);
delete (string *)param;
return 0;
}
};
string *clone = new string(message);
::CreateThread(0, 0,
&message_box::display,
clone, 0, 0);
}
Please, note, that the copy is allocated in the initial thread and destroyed in the new one. This requires multithreading support from your CRT.
In the case new thread fails to start, you'll end up with memory being orphaned. Lets fix this:
void msg(const string &message)
{
struct message_box
{
static DWORD WINAPI display(void *param)
{
auto_ptr<string> message((string *)param);
MessageBox(0, message->c_str(), "Message", 0);
return 0;
}
};
auto_ptr<string> clone(new string(message));
if (::CreateThread(0, 0, &message_box::display, clone.get(), 0, 0))
clone.release(); // release only if the new thread starts successfully.
}
Since the memory is being managed by the CRT, the CRT have to be initialized in the new thread, which is not done by CreateThread API. You have to use CRT beginthread/beginthreadex instead:
void msg(const string &message)
{
struct message_box
{
static unsigned int WINAPI display(void *param)
{
auto_ptr<string> message((string *)param);
MessageBox(0, message->c_str(), "Message", 0);
return 0;
}
};
auto_ptr<string> clone(new string(message));
if (_beginthreadex(0, 0, &message_box::display, clone.get(), 0, 0))
clone.release(); // release only if the new thread starts successfully.
}
This solution leaves aside the problem of the thread itself being leaked as a resource. But, I believe you may find another posts for this on stackoverflow.com :)
thanks )