Stripies
Stripies

Reputation: 81

WinAPI Multithreaded Application

I'm wanting to create a WinAPI application/window and since I don't want my execution to block while waiting for messages, I was planning to have 2 threads; a main thread and an application thread. The application thread would create the window (CreateWindowEx) then block in a message loop.

My predicament comes from the main thread wanting to modify a part of the application. For example, changing the style, size, etc. To keep the application thread-safe, I would assume it is best to keep that kind of code on the same thread. My first idea is to post a message from the main thread so the application thread unblocks and can handle the request and then block again. However, I'm not sure if sending a message from a separate thread is safe and I have had a hard time finding an answer to that online. There may also be better solutions that I'm not considering. I would appreciate any help or feedback.

Upvotes: 1

Views: 227

Answers (1)

Anders
Anders

Reputation: 101569

Sending a message with SendMessage and/or PostMessage across threads is safe and supported.

SendMessage waits while the other thread processes the message and PostMessage does not wait. There are other differences between the two but the important thing to remember in your case is that you cannot do

...
if (whatever)
{
  char buffer[100];
  strcpy(buffer, "hello world");
  PostMessage(g_MyWindow, WM_APP, 0, (LPARAM) buffer); // BUG, must use SendMessage
}
...

because the buffer could go out of scope before the other thread has processed the message.

In general, all the Windows functions that deal with windows like MoveWindow and GetWindowRect are thread safe. Most of them can also be used on windows in another process...

Upvotes: 2

Related Questions