现在的位置: 首页 > 综合 > 正文

简单尝试windows多线程程序

2014年11月14日 ⁄ 综合 ⁄ 共 1085字 ⁄ 字号 评论关闭

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

程序一:函数能并行运行就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。

抱歉!评论已关闭.