API多线程编程的尝试

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]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值