Hi All
Can any one give me thread tutorial?Actually i want to create a thread and call a function.
Printable View
Hi All
Can any one give me thread tutorial?Actually i want to create a thread and call a function.
After read the artical.I am try to write one small example.I am try to call two function.One is calling through Timer and second one is simply call on ClickEvent.Can any one help me tolde it's right or wrong.Quote:
Originally Posted by VictorN
Thanks in advanceCode:void CTestingDemoDlg::OnBnClickedButton1()
{
running = TRUE;
AfxBeginThread(sun, this);
AfxBeginThread(sun1, this);
}
void CTestingDemoDlg::sun()
{
OnStartTimer();
}
void CTestingDemoDlg::sun1()
{
AfxMessageBox(_T("Hello"));
}
UINT CTestingDemoDlg::sun(LPVOID p)
{
CTestingDemoDlg * me = (CTestingDemoDlg *)p;
me->sun();
return 0;
}
void CTestingDemoDlg::OnStop()
{
running = FALSE;
}
UINT CTestingDemoDlg::sun1(LPVOID p)
{
CTestingDemoDlg * me = (CTestingDemoDlg *)p;
me->sun1();
return 0;
}
void CTestingDemoDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
m_test.SetWindowTextW(_T("Sun"));
CDialog::OnTimer(nIDEvent);
}
void CTestingDemoDlg::OnStartTimer()
{
SetTimer(1, 5000, 0);
}
This isn't allowed. First of all, the main thread function needs to be static, and secondly, it is not safe to directly use functions from a dialog inside a thread. Also, calling yourself inside yourself ("me->sun()") is recursive and creates a stack overflow.Code:UINT CTestingDemoDlg::sun(LPVOID p)
{
CTestingDemoDlg * me = (CTestingDemoDlg *)p;
me->sun();
return 0;
}
Well, this variant ("sun1"):is bad because it pops up the message box from the secondary (worker) thread, that you should (must!) avoid.Quote:
Code:UINT CTestingDemoDlg::sun1(LPVOID p)
{
CTestingDemoDlg * me = (CTestingDemoDlg *)p;
me->sun1();
return 0;
}
The variant "sun" looks like not wrong, although I'd not start the timer directly from the worker thread. I'd PostMessage a user defined message to the main GUI thread notifying it that it could (or should) set a timer; then the main thread would choose whether or not set this timer.
Note also, that after every new click of the "Button1" the two new threads will be started.