实验一 :WindowsThreads多线程编程.doc

  1. 1、本文档共13页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
实验一 :WindowsThreads多线程编程

实验 :Windows*Threads多线程编程 模块一:基础练习 4 编译执行, 输出结果: 简答与思考: 写出修改后的HelloThreads的代码。 #include stdafx.h #include windows.h const int numThreads = 4; DWORD WINAPI helloFunc(LPVOID pArg) { int myNum=*((int*)pArg); printf(Hello Thread %d \n,myNum); return 0; } int main() { HANDLE hThread[numThreads]; int tNum[10]; for (int i = 0; i numThreads; i++) { tNum[i]=i; hThread[i] = CreateThread(NULL, 0, helloFunc, tNum[i], 0, NULL ); }WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE); return 0; } 修改后结果 2实验总结 模块二:临界区实验 编译执行, Pi的值为: 编译执行,Pi的值为: 简答与思考: 1 如何进行并行化的?请写出并行化的思路与具体的代码。 // WinPi.cpp : 定义控制台应用程序的入口点 // #include stdafx.h #include windows.h #include time.h static long num_steps=1000000000; double step, pi; CRITICAL_SECTION gCS; //定义全局的临界变量gCS const int numThreads = 2; double dAllSum; DWORD WINAPI PiCalculationThread(LPVOID p) { int j = *(int *)p; double dSum = 0; double dx; int ii; printf(This is the thread %d computing:\n,j); for( ii = j ; ii num_steps ; ii+=numThreads ){ dx = (ii+0.5)*step; dSum = dSum + 4.0/(1.0 + dx*dx); } EnterCriticalSection(gCS); //进入临界区 dAllSum += dSum; LeaveCriticalSection(gCS); //离开临界区 printf(The thread %d computation has finished:\n,j); return 0; } int _tmain(int argc, _TCHAR* argv[]) { clock_t start1; clock_t stop1; start1= clock(); //开始计时 HANDLE PiCalculation[numThreads]; int tmp[numThreads]; step = 1.0/(double) num_steps; InitializeCriticalSection(gCS); for( int ia = 0 ; ia numThreads ; ia++ ){ tmp[ia] = ia; PiCalculation[ia] = CreateThread(NULL , 0 , PiCalculationThread , tmp[ia] , 0 , NULL); } WaitForMultipleObjects (numThreads,PiCalculation,TRUE,INFINITE); DeleteCriticalSection(gCS); pi = step * dAllSum; printf(Pi = %12.9f\n,pi); stop1 = clock(); //停止计时 printf(The time of calculation was %f seconds \n,(double)(stop1 - start1)/1000.0); //输出运行时间 } 2 在本实验中,哪些变量是需要保护的?采取什么方法实现的? dAllSum变量需要保护 EnterCriticalSection(gCS); //进入临界区 dAllSum += d

文档评论(0)

yan698698 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档