文档详情

多核多线程技术WINAPI_实验报告1.doc

发布:2017-07-06约8.17千字共13页下载文档
文本预览下载声明
实验 :Windows*Threads多线程编程 模块一:基础练习 4 编译执行, 输出结果: 简答与思考: 写出修改后的HelloThreads的代码。 // HelloWorld.cpp : 定义控制台应用程序的入口点 #include stdafx.h #include windows.h const int numThreads=4; DWORD WINAPI helloFunc(LPVOID arg){ int myNum=*((int*)arg); printf(HelloThread %d\n,myNum); return 0; } int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThread[numThreads]; int tNum[numThreads]; for(int i=0;inumThreads;i++) { tNum[i]=i; hThread[i]=CreateThread(NULL,0,helloFunc,tNum[i],0,NULL); } WaitForMultipleObjects(numThreads,hThread,true,INFINITE); return 0; } 实验总结 模块二:临界区实验 3 编译执行, Pi的值为: 6 并行程序编译执行,Pi的值为: 简答与思考: 1 如何进行并行化的?请写出并行化的思路与具体的代码。 依据刚获得的本线程序号,以步进长度(线程总数)间隔地累加求和,好比线程0求和第0、2、4、6、8……块,线程1求和第1、3、5、7、9……块。for(int i=myNum;inum_steps;i+=numthreads) { x=(i+0.5)*step; multhread+=4.0/(1.0+x*x); } 这部分在多线程并行部分之外,是由单线程执行的,作用是将前述各个线程独立间隔求和的结果汇总,得到完整的和,也就是数值积分结果。// CriticalSectionPi.cpp : 定义控制台应用程序的入口点 #include stdafx.h #include windows.h #include time.h const int numthreads=2; static long num_steps=1000000; double step=0.0; double pi=0.0,sum=0.0; CRITICAL_SECTION cs; DWORD WINAPI Func(LPVOID arg) { int myNum=*((int*)arg); double sum1=1.0,x; for(int i=myNum;inum_steps;i+=numthreads) { x=(i+0.5)*step; sum1+=4.0/(1.0+x*x); } EnterCriticalSection(cs); sum+=sum1; LeaveCriticalSection(cs); return 0; } int _tmain(int argc, _TCHAR* argv[]) { clock_t start,stop; start=clock(); HANDLE hthread[numthreads]; int tNum[numthreads]; InitializeCriticalSection(cs); step=1.0/(double)num_steps; for(int i=0;inumthreads;++i) { tNum[i]=i; hthread[i]=CreateThread(NULL,0,Func,tNum[i],0,NULL); } WaitForMultipleObjects(numthreads,hthread,true,INFINITE); DeleteCriticalSection(cs); pi=step*sum; stop=clock(); printf(Pi=%12.9f\n,pi); printf(The time of calculation was %0.12f seconds\n,((double)(stop-start)/1000.0)); return 0; } 2 在本实验中,哪些变量是需要保护的?采取什么方法实现的? 将sum1累加到sum中,sum是临界区代码,需要保护,因为其是引起数据竞争的关键;采用把其设置成为临界区代码的方法实现。 EnterCriticalSection(cs); sum+=sum1; LeaveCrit
显示全部
相似文档