1、编写线程需要调用的函数,DWORD WINAPI ThreadFun1(LPVOID lpParameter);
在头文件中,声明一个临界区对象: CRITICAL_SECTION m_csCommuictationSync;
在函数执行前调用EnterCriticalSection(&pForm->m_csCommuictationSync);进入临界区,执行结束后调用LeaveCriticalSection(&pForm->m_csCommuictationSync);退出临界区;进入
和退出临界区函数只能用别名作为参数,不能直接用指针蛮量;
退出线程:ExitThread(0);
//函数1
DWORD WINAPI ThreadFun1(LPVOID lpParameter)
{
//
int i,j,k,tempi,tempj,tempk;
TFormWin32Thread *pForm;
String s;
pForm = (TFormWin32Thread *)lpParameter;
EnterCriticalSection(&pForm->m_csCommuictationSync);
for (i = 1; i < 10; i++) {
tempi = i*i*i;
for (j = 0; j < 10; j++) {
tempj = tempi + j*j*j;
for(k = 0;k < 10;k++)
{
tempk = tempj + k*k*k;
if (tempk == 100*i + 10*j + k) {
s = IntToStr(tempk);
pForm->Memo1->Lines->Add(s);
}
}
}
}
LeaveCriticalSection(&pForm->m_csCommuictationSync);
ExitThread(0);
return 0;
}
//函数2
DWORD WINAPI ThreadFun2(LPVOID lpParameter)
{
//
int i,j,temp,temp1;
TFormWin32Thread *pForm;
String s;
pForm = (TFormWin32Thread *)lpParameter;
EnterCriticalSection(&pForm->m_csCommuictationSync);
for(i = 2;i < 5000;i++)
{
//long double temp2 = sqrt(i);
temp1 = (int)sqrtl(i);
for(j = 2;j < temp1;j++)
{
temp = i/j;
if(temp*j == i)
break;
}
if(j > temp1)
{
s = IntToStr(i);
pForm->Memo1->Lines->Add(s);
}
}
LeaveCriticalSection(&pForm->m_csCommuictationSync);
return 0;
}
创建线程:
初始化临界区:InitializeCriticalSection(&m_csCommuictationSync);
创建线程:CreateThread(NULL,0,ThreadFun2,(void *)this,CREATE_SUSPENDED,&threadID[0]);
恢复线程:ResumeThread(hThread[0]);
//创建线程
void __fastcall TFormWin32Thread::Button1Click(TObject *Sender)
{
HANDLE hThread[2];
DWORD threadID[2];
this->Memo1->Clear();
InitializeCriticalSection(&m_csCommuictationSync);
hThread[0] = CreateThread(NULL,0,ThreadFun2,(void *)this,CREATE_SUSPENDED,&threadID[0]);
ResumeThread(hThread[0]);
hThread[1] = CreateThread(NULL,0,ThreadFun1,(void *)this,0,&threadID[1]);
}