Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use PostMessage() like this?

I am currently working on an MFC project, which runs several threads and uses PostMessage() for the message exchange between the worker thread and the Main UI thread.

I wrote a code like below:

UINT ThreadFunc (LPVOID pParam) {
    pointerToMainUI->PostMessage(WM_EXAMPLE, MSG_EXAMPLE_1, 1);    
    pointerToMainUI->PostMessage(WM_EXAMPLE, MSG_EXAMPLE_2, 2); // Question 1
}

void MyDialogExClass::OnBnClickedStart() {
    int intA = 0; // Declared in header as public global

    mThreadA = AfxBeginThread(ThreadFunc , this);
    mThreadB = AfxBeginThread(ThreadFunc , this); // Question 2
}

LRESULT MyDialogExClass::WinProc (WPARAM wParam, LPARAM lParam) {
    
    int iParam = (int)lParam;

    switch (wParam) {
    case MSG_EXAMPLE_1:
        intA = iParam;
        break;

    case MSG_EXAMPLE_2:
        // Do Something
        break;
    }
    
    return LRESULT();
}

It is important for my application to do FIFO, which had me wonder if my data and memory is at any risk.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My Question:

  1. Is it safe for me to have the thread do two PostMessage() calls in a row?

  2. Is it safe for me to have two different threads running that will change the value of a variable from the main thread?

>Solution :

  1. In this case, yes. Your posted values are fully contained inside the lParam of the messages, so there is no cross-threading issue to post them. If you were posting pointers to values, that would be a different story.

  2. In this case, yes. You are not updating the variable directly in your threads, you are delegating the values to the main UI thread, and then it is updating the variable. The messages will be processed one at a time, and the message queue will ensure they are processed in the order that they are posted.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading