简单尝试windows多线程程序

这两天因工作需要,写了个算法,计算复杂度较高。期望利用多核机器的优势,并行计算,加快运行速度。简单看了看资料,尝试两个小程序。

程序一:函数能并行运行就OK。

DWORD WINAPI Fun(LPVOID lpParamter)
{

	  cout<<"Fun display"endl; 
	  i++;
}

int main (void)
{
	cout << "Now starting to verify multi-thread on windows" << endl;

	HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
    CloseHandle(hThread);
    while(1) 
	{ 
		cout<<"main display!"<<endl;  
		Sleep(2000);
	}

	cout << "Press anykey to bye-bye" << endl;
	getchar();

	return 0;
}

程序二:传个参数进到并发函数中,如下:

DWORD WINAPI Fun(LPVOID lpParamter)
{
	int iCount = *((int*)lpParamter);
	int i = 0;
    while(i < iCount) 
	{ 
	  cout<<"Fun display in the "<< i << " times" <<endl; 
	  i++;
	  // Sleep(1000);
	}
	return iCount;
}


int main (void)
{
	cout << "Now starting to verify multi-thread on windows" << endl;

    int i = 1000;
    HANDLE hThread = CreateThread(NULL, 0, Fun, &i, 0, NULL);
    CloseHandle(hThread);
    while(1) 
	{ 
		cout<<"main display!"<<endl;  
		Sleep(2000);
	}

	getchar();

	return 0;
}
程序三:在写上两个程序的时候,听说OpenMP神器,尝试一下

int main (void)
{
	cout << "Now starting to verify multi-thread on windows" << endl;

	int iArray [100];
	for (int i=0; i<100; i++)
		iArray[i] = i;

	#pragma omp parallel for num_threads(2)
	for (int i=0; i<100; i++)
		cout << iArray[i] << endl;

	getchar();

	return 0;
}
运行的时候,可以看到:1. 双核都在计算;2. 数组实际上是乱序输出(多个线程并发的结果)。


最后我工作中采用的是OpenMP。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值