Andrei Vieru
Andrei Vieru

Reputation: 174

threads sync with events

Newbie to embedded systems here. I have to synchronize two threads with events. My code show only "Show in edit box 2sec" and is not going to secondthread to show what I have there. I should show in an edit box for 2 seconds with one thread a message and after two seconds i should show for 3 seconds another message. This should be repeat forever.

void FirstThread(void)
{

    int i;
    //write data to edit box
    CString szEdit;
    szEdit.Format(_T("Show in edit box 2sec"));
    m_editbox->SetWindowText(szEdit);


    while(1){

        WaitForSingleObject (hEvent, INFINITE);
        for(i=0;i<1;i++){
            Sleep(2000);
        }
        SetEvent (hEvent);
    }

}

void SecondThread (void)
{
    int i;

    //write data to edit box
    CString szEdit;
    szEdit.Format(_T("Show in edit box 3 sec"));
    m_editbox->SetWindowText(szEdit);

    while(1){
        WaitForSingleObject (hEvent, INFINITE);
        for(i=0;i<1;i++){
            Sleep(3000); 
        }
        SetEvent (hEvent);
    }
}

Upvotes: 0

Views: 88

Answers (2)

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10415

There are problems with your approach. MFC will not permit you to access a control from a thread that did not create it, and placing WaitForSingleObject or Sleep within the main thread stops it from processing messages so the program becomes "unresponsive".

You could do this with no threads, no WaitForSingleObject, no Sleep and no events by using a timer in the main thread. The main thread would initially call SetTimer, then process the WM_TIMER message to change the control text periodically. Meanwhile, the program would be able to process any other messages normally, between the WM_TIMER messages.

Upvotes: 0

shakurov
shakurov

Reputation: 2518

You should use two different events, one signaling the end of sleeping in the first thread, the other one - in the second thread. (Initially, one of these events should be set (signaled), the other - unset.)

Upvotes: 1

Related Questions