多核编程与并行计算实验报告 (1)

合集下载

并行计算的实验

并行计算的实验

实验一多线程计算π,性能分析1.1 实验内容多线程计算π,性能分析1.2 实验原理1.3实现方法编程语言:c++多线程:windows 多线程thread平台:windows 7600(32bit),Lenovo T400 Laptop ,IntelCore 2 Duo P8400 @ 2.26GHz集成开发环境:Visual Studio Team System 2008(32bit)1.4程序流程图NN i dx x Ni 15.0141402102⨯⎪⎪⎭⎫⎝⎛++≈+=∑⎰≤≤π1.5实验结果线程数NUM_THREAD=4N π Time-cost100 3.14160098692312 3ms1000 3.14159273692313 4ms10000 3.14159265442313 5ms100000 3.14159265359813 25ms1000000 3.14159265358990 82ms1.6性能分析精度随叠加次数N的增大而趋近于π的真实值,计算时间也随之增高;相同的叠加次数下,因为是双核处理器,线程数为2时计算性能最高。

理论性能提升有极限值,所以不会因为线程的增多而性能无限增强。

当线程数很大时,计算时间增加很快。

1.7总结展望第一次编写并行化的程序,对多线程编程有了初步的认识。

由于是在Visual Studio平台下编程,很多知识是从Lunix平台移植过来的,虽然表现形式有少许差别,但核心思想一致。

通过学习,对windows多线程编程有了一定的掌握。

实验二3PCF计算多线程实现2.1实验内容▪定义:–点集D、R。

–定义D中的点为a i∈D,R中的点为b i∈R。

–距离:r1、r2、r3、err▪求:–满足以下条件的三元组(空间中三角形)的数目•<a i, b m, b n>,|a i-b m|=r1±err且|a i-b n|=r2±err且|b m-b n|=r3±err2.2实验原理对于D中每一点a i,在R中找到与之距离为r1的点集R’,找到与之距离为r2的点集R’’。

多核编程与并行计算实验报告 (1)

多核编程与并行计算实验报告 (1)

(此文档为word格式,下载后您可任意编辑修改!) 多核编程与并行计算实验报告姓名:日期:2014年 4月20日实验一// exa1.cpp : Defines the entry point for the console application. //#include"stdafx.h"#include<windows.h>#include<process.h>#include<iostream>#include<fstream>using namespace std;void ThreadFunc1(PVOID param){while(1){Sleep(1000);cout<<"This is ThreadFunc1"<<endl;}}void ThreadFunc2(PVOID param){while(1){Sleep(1000);cout<<"This is ThreadFunc2"<<endl;}}int main(){int i=0;_beginthread(ThreadFunc1,0,NULL);_beginthread(ThreadFunc2,0,NULL);Sleep(3000);cout<<"end"<<endl;return 0;}实验二// exa2.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream>using namespace std;DWORD WINAPI FunOne(LPVOID param){while(true){Sleep(1000);cout<<"hello! ";}return 0;}DWORD WINAPI FunTwo(LPVOID param){while(true){Sleep(1000);cout<<"world! ";}return 0;}int main(int argc, char* argv[]){int input=0;HANDLE hand1=CreateThread (NULL, 0, FunOne, (void*)&input, CREATE_SUSPENDED,NULL);HANDLE hand2=CreateThread (NULL, 0, FunTwo, (void*)&input, CREATE_SUSPENDED, NULL);while(true){cin>>input;if(input==1){ResumeThread(hand1);ResumeThread(hand2);}else{SuspendThread(hand1);SuspendThread(hand2);}};TerminateThread(hand1,1);TerminateThread(hand2,1);return 0;}实验三// exa3.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream>using namespace std;int globalvar = false;DWORD WINAPI ThreadFunc(LPVOID pParam){cout<<"ThreadFunc"<<endl;Sleep(200);globalvar = true;return 0;}int main(){HANDLE hthread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);if (!hthread){cout<<"Thread Create Error ! "<<endl;CloseHandle(hthread);}while (!globalvar)cout<<"Thread while"<<endl;cout<<"Thread exit"<<endl;return 0;}实验四:// exa4.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<process.h>#include<iostream>#include<fstream>using namespace std;HANDLE evRead, evFinish;void ReadThread(LPVOID param){WaitForSingleObject (evRead ,INFINITE);cout<<"Reading"<<endl;SetEvent (evFinish);}void WriteThread(LPVOID param){cout<<"Writing"<<endl;SetEvent (evRead);}int main(int argc , char * argv[]){evRead = CreateEvent (NULL ,FALSE ,FALSE ,NULL) ;evFinish = CreateEvent (NULL ,FALSE ,FALSE ,NULL) ;_beginthread(ReadThread , 0 , NULL) ;_beginthread(WriteThread , 0 , NULL) ;WaitForSingleObject (evFinish,INFINITE) ;cout<<"The Program is End"<<endl;return 0 ;}实验五// exa5.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<process.h>#include<iostream>#include<fstream>using namespace std;int total = 100 ;HANDLE evFin[2] ;CRITICAL_SECTION cs ;void WithdrawThread1(LPVOID param){EnterCriticalSection(&cs) ;if ( total-90 >= 0){total -= 90 ;cout<<"You withdraw 90"<<endl;}elsecout<<"You do not have that much money"<<endl;LeaveCriticalSection(&cs) ;SetEvent (evFin[0]) ;}void WithdrawThread2(LPVOID param){EnterCriticalSection(&cs) ;if ( total-20 >= 0){total -= 20 ;cout<<"You withdraw 20"<<endl;}elsecout<<"You do not have that much money"<<endl;LeaveCriticalSection(&cs) ;LeaveCriticalSection(&cs) ;SetEvent (evFin[1]) ;}int main(int argc , char * argv[]){evFin[0] = CreateEvent (NULL,FALSE,FALSE,NULL) ;evFin[1] = CreateEvent (NULL,FALSE,FALSE,NULL) ;InitializeCriticalSection(&cs) ;_beginthread(WithdrawThread1 , 0 , NULL) ;_beginthread(WithdrawThread2 , 0 , NULL) ;WaitForMultipleObjects(2 ,evFin ,TRUE ,INFINITE) ;DeleteCriticalSection(&cs) ;cout<<total<<endl;return 0 ;}实验六:// exa6.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream.h>#define THREAD_INSTANCE_NUMBER 3LONG g_fResourceInUse = FALSE;LONG g_lCounter = 0;DWORD ThreadProc(void * pData) {int ThreadNumberTemp = (*(int*) pData);HANDLE hMutex;cout << "ThreadProc: "<< ThreadNumberTemp << " is running!" << endl;if ((hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "Mutex.Test")) == NULL) { cout << "Open Mutex error!" << endl;}cout << "ThreadProc " << ThreadNumberTemp << " gets the mutex"<< endl;ReleaseMutex(hMutex);CloseHandle(hMutex);return 0;}int main(int argc, char* argv[]){int i;DWORD ID[THREAD_INSTANCE_NUMBER];HANDLE h[THREAD_INSTANCE_NUMBER];HANDLE hMutex;if ( (hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "Mutex.Test")) == NULL) { if ((hMutex = CreateMutex(NULL, FALSE, "Mutex.Test")) == NULL ) {cout << "Create Mutex error!" << endl;return 0;}}for (i=0;i<THREAD_INSTANCE_NUMBER;i++){h[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc,(void *)&ID[i],0,&(ID[i]));if (h[i] == NULL)cout << "CreateThread error" << ID[i] << endl;elsecout << "CreateThread: " << ID[i] << endl;}WaitForMultipleObjects(THREAD_INSTANCE_NUMBER,h,TRUE,INFINITE);cout << "Close the Mutex Handle! " << endl;CloseHandle(hMutex);return 0;}实验七// exa7.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream.h>#define THREAD_INSTANCE_NUMBER 3DWORD foo(void * pData) {int ThreadNumberTemp = (*(int*) pData);HANDLE hSemaphore;cout << "foo: "<< ThreadNumberTemp << " is running!" << endl;if ((hSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, "Semaphore.Test")) == NULL) {cout << "Open Semaphore error!" << endl;}cout << "foo " << ThreadNumberTemp << " gets the semaphore"<< endl;ReleaseSemaphore(hSemaphore, 1, NULL);CloseHandle(hSemaphore);return 0;}int main(int argc, char* argv[]){int i;DWORD ThreadID[THREAD_INSTANCE_NUMBER];HANDLE hThread[THREAD_INSTANCE_NUMBER];HANDLE hSemaphore;if ((hSemaphore = CreateSemaphore(NULL,0,1, "Semaphore.Test")) == NULL ) { cout << "Create Semaphore error!" << endl;return 0;}for (i=0;i<THREAD_INSTANCE_NUMBER;i++){hThread[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) foo,(void *)&ThreadID[i],0,&(ThreadID[i]));if (hThread[i] == NULL)cout << "CreateThread error" << ThreadID[i] << endl;elsecout << "CreateThread: " << ThreadID[i] << endl;}WaitForMultipleObjects(THREAD_INSTANCE_NUMBER,hThread,TRUE,INFINITE);cout << "Close the Semaphore Handle! " << endl;CloseHandle(hSemaphore);return 0;}实验八:// exa8.cpp : Defines the class behaviors for the application.//#include"stdafx.h"#include"exa8.h"#include"MainFrm.h"#include"exa8Doc.h"#include"exa8View.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CExa8AppBEGIN_MESSAGE_MAP(CExa8App, CWinApp)//{{AFX_MSG_MAP(CExa8App)ON_COMMAND(ID_APP_ABOUT, OnAppAbout)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSG_MAP// Standard file based document commandsON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)END_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CExa8App constructionCExa8App::CExa8App(){// TODO: add construction code here,// Place all significant initialization in InitInstance}/////////////////////////////////////////////////////////////////////////////// The one and only CExa8App objectCExa8App theApp;/////////////////////////////////////////////////////////////////////////////// CExa8App initializationBOOL CExa8App::InitInstance(){AfxEnableControlContainer();// Standard initialization// If you are not using these features and wish to reduce the size// of your final executable, you should remove from the following// the specific initialization routines you do not need.#ifdef _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL #elseEnable3dControlsStatic(); // Call this when linking to MFC statically#endif// Change the registry key under which our settings are stored.// TODO: You should modify this string to be something appropriate// such as the name of your company or organization.SetRegistryKey(_T("Local AppWizard-Generated Applications"));LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates// serve as the connection between documents, frame windows and views.CSingleDocTemplate* pDocTemplate;pDocTemplate = new CSingleDocTemplate(IDR_MAINFRAME,RUNTIME_CLASS(CExa8Doc),RUNTIME_CLASS(CMainFrame), // main SDI frame windowRUNTIME_CLASS(CExa8View));AddDocTemplate(pDocTemplate);// Parse command line for standard shell commands, DDE, file openCCommandLineInfo cmdInfo;ParseCommandLine(cmdInfo);// Dispatch commands specified on the command lineif (!ProcessShellCommand(cmdInfo))return FALSE;// The one and only window has been initialized, so show and update it.m_pMainWnd->ShowWindow(SW_SHOW);m_pMainWnd->UpdateWindow();return TRUE;}/////////////////////////////////////////////////////////////////////////////// CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialog{public:CAboutDlg();// Dialog Data//{{AFX_DATA(CAboutDlg)enum { IDD = IDD_ABOUTBOX };//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAboutDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL// Implementationprotected://{{AFX_MSG(CAboutDlg)// No message handlers//}}AFX_MSGDECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) {//{{AFX_DATA_INIT(CAboutDlg)//}}AFX_DATA_INIT}void CAboutDlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAboutDlg)//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)// No message handlers//}}AFX_MSG_MAPEND_MESSAGE_MAP()// App command to run the dialogvoid CExa8App::OnAppAbout(){CAboutDlg aboutDlg;aboutDlg.DoModal();}/////////////////////////////////////////////////////////////////////////////// CExa8App message handlers、实验九:using System;using System.Threading;class Test{static void Main(){ThreadStart threadDelegate = new ThreadStart(Work.DoWork);Thread newThread = new Thread(threadDelegate);newThread.Start();Work w = new Work();w.Data = 42;threadDelegate = new ThreadStart(w.DoMoreWork);newThread = new Thread(threadDelegate);newThread.Start();}}class Work{public static void DoWork(){Console.WriteLine("Static thread procedure.");}public int Data;public void DoMoreWork(){Console.WriteLine("Instance thread procedure. Data={0}", Data);}}实验十:using System;using System.Threading;class Test{static int total = 100;public static void WithDraw1(){int n=90;if (n <= total){total -= n;Console.WriteLine("You have withdrawn. n={0}", n);Console.WriteLine("total={0}", total);}else{Console.WriteLine("You do not enough money. n={0}", n);Console.WriteLine("total={0}", total);}}public static void WithDraw2(){int n = 20;if (n <= total){total -= n;Console.WriteLine("You have withdrawn. n={0}", n);Console.WriteLine("total={0}", total);}else{Console.WriteLine("You do not enough money. n={0}", n);Console.WriteLine("total={0}", total);}}public static void Main(){ThreadStart thread1 = new ThreadStart(WithDraw1);Thread newThread1 = new Thread(thread1);ThreadStart thread2 = new ThreadStart(WithDraw2);Thread newThread2 = new Thread(thread2);newThread1.Start();newThread2.Start();}}实验十一:// exa11.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<conio.h>#include<stdio.h>#define THREAD_INSTANCE_NUMBER 3LONG g_fResourceInUse = FALSE;LONG g_lCounter = 0;CRITICAL_SECTION cs;DWORD ThreadProc1(void * pData) {int ThreadNumberTemp = (*(int*) pData);printf("ThreadProc1: %d is running!\n",ThreadNumberTemp );EnterCriticalSection(&cs);printf("ThreadProc1 %d enters into critical section\n",ThreadNumberTemp);Sleep(1000);LeaveCriticalSection(&cs);return 0;}DWORD ThreadProc2(void * pData) {int ThreadNumberTemp = (*(int*) pData);printf("ThreadProc2: %d is running!\n",ThreadNumberTemp );EnterCriticalSection(&cs);printf("ThreadProc2 %d enters into critical section\n",ThreadNumberTemp);Sleep(1000);LeaveCriticalSection(&cs);return 0;}int main(int argc, char* argv[]){int i;DWORD ID1,ID2;HANDLE h1,h2;InitializeCriticalSection(&cs);printf("Create the critical section \n");h1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc1,(void *)&ID1,0,&(ID1));if (h1 == NULL)printf("CreateThread error %d \n",ID1);elseprintf("CreateThread %d \n",ID1);h2= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc2,(void *)&ID2,0,&(ID2));if (h2== NULL)printf("CreateThread error %d \n",ID2);elseprintf("CreateThread %d \n",ID2);WaitForSingleObject (h1,INFINITE);WaitForSingleObject (h2,INFINITE);printf("Delete the critical section \n");DeleteCriticalSection(&cs);getch();return 0;}。

并行程序实验报告

并行程序实验报告

并行程序设计实验报告姓名:学号:一、实验目的通过本次试验,了解使用OpenMP编程的基本方法和MPI的编程方法,通过实践实现的基本程序,掌握基本的线程及进程级并行应用开发技术,能够分析并行性能瓶颈及相应优化方法。

二、实验环境Linux操作系统,mpi库,多核处理器三、实验设计与实现(一)MPI并行程序设计用MPI编写一个greeting程序,编号为0的进程接受其它各进程的“问候”,并在计算机屏幕上显示问候情况。

用MPI编写一个多进程求积分的程序,并通过积分的方法求π的值,结果与π的25位精确值比较。

(二)多线程程序设计用Pthreads或OpenMP编写通过积分的方法求π的程序。

把该程序与相应的MPI程序比较。

用Pthreads或OpenMP编写编写矩阵相乘的程序,观察矩阵增大以及线程个数增减时的情形。

四、实验环境安装(一)MPI环境安装1.安装kylin操作系统的虚拟机(用VirtualBox)2.安装增强功能,使之与windows主机能够文件共享。

3.拷贝mpich-3.0.4.tar.gz到/root/myworkspace/目录下,并解压(tar xzf mpich-3.0.4.tar.gz)4.下面开始安装mkdir /root/myworkspace/mpi./configure --prefix=/root/myworkspace/mpi --disable-f77 --disable-fcmakemake install5.配置环境变量打开/root/.bashrc文件,在文件的末尾加上两行:PATH=$PATH:/root/myworkspace/mpi/binexport PATH保存退出,然后执行命令source /root/.bashrc(二)openMP实验环境安装Visual Studio中修改:项目->属性->c/c++->语言,将“OpenMP支持”改成“是”:五、实验结果及分析(一)MPI并行程序设计实验一:问候发送与接收非零号进程将问候的信息发送给0号进程,0号进程依次接收其它进程发送过来的消息并将其输出。

C语言中的并行计算与多核处理器编程

C语言中的并行计算与多核处理器编程

C语言中的并行计算与多核处理器编程C语言是一门广泛应用于嵌入式系统、操作系统和科学计算等领域的高级编程语言。

它以其高效性和灵活性而闻名,而并行计算和多核处理器编程是当今计算机领域中的热门话题。

本文将详细介绍C语言中的并行计算和多核处理器编程,包括并行计算的概念、多核处理器的原理以及如何有效地在C语言中实现并行计算。

一、并行计算的概念并行计算是指多个操作同时进行,以提高计算速度和系统性能的计算方式。

与串行计算不同,串行计算是指按照顺序逐个执行操作。

并行计算的主要形式有数据并行和任务并行。

数据并行是指将大规模的数据集分解成多个小规模的数据集,然后分配给多个处理器同时处理。

任务并行是指将一个大任务分解成多个小任务,然后分配给多个处理器同时执行。

二、多核处理器的原理多核处理器是指在一个物理芯片上集成了多个处理器核心,每个处理器核心都具有独立的运算和存储能力。

多核处理器通过并行计算的方式,可以同时执行多个任务,提高系统的性能。

多核处理器采用了多级缓存、数据共享和并行调度等技术,以实现任务的分配和协调,从而更有效地利用处理器的资源。

三、C语言中的并行计算在C语言中实现并行计算需要依赖并行计算库和多线程编程技术。

常用的并行计算库有OpenMP和MPI。

OpenMP是一种基于共享内存的并行计算库,可以通过在代码中插入指令来实现并行化。

MPI是一种基于消息传递的并行计算库,用于在不同处理器之间进行通信和协调。

同时,C语言还提供了多线程编程技术,可以通过创建多个线程来实现并行计算。

四、多核处理器编程在多核处理器编程中,任务的划分和调度是关键。

可以通过任务划分和负载均衡来实现有效的并行计算。

任务划分是将一个大任务分解成多个小任务,然后分配给多个处理器核心执行。

负载均衡是保持各个处理器核心的工作量大致相同,避免出现任务执行时间过长或者某个处理器核心空闲的情况。

在C语言中,可以使用线程库如pthread来创建多个线程,并利用线程的特性进行任务划分和负载均衡。

并行程序设计实验报告

并行程序设计实验报告

并行程序设计实验报告实验报告:并行程序设计一、实验目的本实验旨在通过并行程序设计,提高程序的执行效率和性能,减少串行程序在处理大规模数据时出现的效率瓶颈。

二、实验原理1.任务划分:将大规模的任务划分成多个可并行执行的子任务。

2.任务分配:将各个子任务分配给不同的计算单元(如多线程、多进程、多核)进行处理。

3.任务合并:将各个子任务的计算结果进行合并,得到最终的结果。

三、实验内容本次实验主要涉及多线程编程和数据并行编程。

1.多线程编程多线程编程是指在一个单独的程序中同时运行多个线程,利用系统的多核资源来提高程序的执行效率。

多线程编程可以通过线程的创建、启动、运行和同步等操作来实现。

在本实验中,我们将使用C++编程语言,并利用其提供的多线程库来实现多线程编程。

具体步骤如下:(1)使用pthread库创建并启动多个线程。

(2)利用线程同步机制(如互斥锁、信号量等)保证线程的正确执行顺序和数据的正确性。

(3)通过编写并行程序,将大规模任务划分成多个子任务,并分配给不同的线程进行处理。

2.数据并行编程数据并行编程是指将大规模的数据划分成多个小块,并分配给多个计算单元(如GPU)进行并行处理。

每个计算单元都执行相同的计算操作,但操作的数据不同。

在本实验中,我们将使用CUDA平台进行数据并行编程。

(1)利用CUDA编程模型,将计算任务划分成多个线程块,并分配给不同的计算单元执行。

(2)通过编写并行程序,实现数据的划分和映射、任务的分配和协调。

四、实验结果经过多次实验,我们发现并行程序设计在处理大规模数据时能够显著提高程序的执行效率和性能。

相比于串行程序,多线程编程和数据并行编程分别提高了X%和Y%的执行速度。

同时,我们也发现在设计并行程序时,要考虑到数据的划分和映射、任务的分配和协调、线程的同步和通信等方面的问题。

这些问题对于程序的性能和正确性都有着重要的影响。

五、实验总结通过本次实验,我们了解到并行程序设计的基本原理和技术,以及它在优化程序性能和提高执行效率方面的重要作用。

并行计算实验一报告

并行计算实验一报告

并行计算实验一报告广东技术师范学院实验报告计算机科学与学院: 计算机科学学院专业: 班级: 成绩: 技术姓名: 学号: 组别: 组员: 实验地点: 工业中心203 实验日期: 指导教师签名: 预习情况操作情况考勤情况数据处理情况实验 (一) 项目名称: 建立并行计算平台一、实验目的在一个局域网中建立能够互相通信的两台计算机,为以后实验建立一个实验平台。

二、实验内容:1.1 系统要求安装MPICH for Microsoft Windows 对系统有如下要求:Windows NT4/2000/XP 的Professional 或Server 版(不支持Windows 95/98) 所有主机必须能够建立TCP/IP 连接MPICH 支持的编译器有:MS VC++ 6.x,MS VC++.NET,Compaq Visual Fortran 6.x,Intel Fortran,gcc ,以及g77 。

安装MPICH ,必须以管理员的身份登录。

1.2 安装以管理员的身份登录每台主机,在所有主机上建立一个同样的账户(当然也可以每个机器使用不同的用户名和账户,然后建立一个配置文件,使用命令行的方式运行程序),然后,运行下载的安装文件,将MPICH 安装到每台主机上。

打开“任务管理器”中的“进程”选项卡,查看是否有一个mpd.exe 的进程。

如果有的话说明安装成功。

以后每次启动系统,该进程将自动运行。

打开任务管理器如下:1.3 注册与配置安装好MPICH 之后还必须对每台计算机进行注册和配置才能使用。

其中注册必须每台计算机都要进行,配置只要在主控的计算机执行就行了。

注册的目的是,将先前在每台计算机上申请的账号与密码注册到MPICH 中去,这样MPICH 才能在网络环境中访问每台主机。

配置方法:运行“mpich\mpd\bin\MPIRegister.exe”首先会提示输入用户账号,然后会提示输入两边密码,之后会问你是否保持上面的设定。

并行计算实验报告一

并行计算实验报告一

并行计算实验报告一江苏科技大学计算机科学与工程学院实验报告评定成绩指导教师实验课程:并行计算宋英磊实验名称:Java多线程编程学号: 姓名: 班级: 完成日期:2014年04月22日1.1 实验目的(1) 掌握多线程编程的特点;(2) 了解线程的调度和执行过程;(3) 掌握资源共享访问的实现方法。

1.2 知识要点1.2.1线程的概念(1) 线程是程序中的一个执行流,多线程则指多个执行流;(2) 线程是比进程更小的执行单位,一个进程包括多个线程;(3) Java语言中线程包括3部分:虚拟CPU、该CPU执行的代码及代码所操作的数据。

(4) Java代码可以为不同线程共享,数据也可以为不同线程共享; 1.2.2 线程的创建(1) 方式1:实现Runnable接口Thread类使用一个实现Runnable接口的实例对象作为其构造方法的参数,该对象提供了run方法,启动Thread将执行该run方法;(2) 方式2:继承Thread类重写Thread类的run方法;1.2.3 线程的调度(1) 线程的优先级, 取值范围1,10,在Thread类提供了3个常量,MIN_PRIORITY=1、MAX_ PRIORITY=10、NORM_PRIORITY=5;, 用setPriority()设置线程优先级,用getPriority()获取线程优先级; , 子线程继承父线程的优先级,主线程具有正常优先级。

(2) 线程的调度:采用抢占式调度策略,高优先级的线程优先执行,在Java 中,系统按照优先级的级别设置不同的等待队列。

1.2.4 线程的状态与生命周期说明:新创建的线程处于“新建状态”,必须通过执行start()方法,让其进入到“就绪状态”,处于就绪状态的线程才有机会得到调度执行。

线程在运行时也可能因资源等待或主动睡眠而放弃运行,进入“阻塞状态”,线程执行完毕,或主动执行stop方法将进入“终止状态”。

1.2.5 线程的同步--解决资源访问冲突问题(1) 对象的加锁所有被共享访问的数据及访问代码必须作为临界区,用synchronized加锁。

多核计算与并行程序设计

多核计算与并行程序设计

多核计算与并行程序设计随着计算机技术的不断发展,多核处理器已经成为计算机系统中常见的组成部分。

多核处理器具有多个处理核心,每个核心都可以并行处理不同的指令。

并行计算技术的出现,提高了计算机系统的性能和效率。

在多核计算的背景下,同时也引发了并行程序设计的需求和挑战。

多核计算的出现,为我们提供了更大的计算资源。

通过将计算任务分配到不同的核心上,可以使程序并行执行,从而提高系统的运算速度。

传统的串行程序在多核计算系统中并不能充分利用计算资源,需要通过并行程序设计来进行优化。

并行程序设计强调任务的分解和分配。

首先,需要将程序分解成适合并行执行的子任务,然后将这些子任务分配到不同的处理核心上进行执行。

在分解和分配的过程中,要考虑任务间的依赖关系和互斥访问问题。

如果任务之间存在依赖关系,需要合理安排任务的执行顺序,保证依赖关系得到满足。

同时,如果多个任务需要同时访问共享的资源,如内存或文件,需要采取合适的同步机制,以避免数据竞争和冲突。

并行程序设计的核心是任务分解和任务调度。

任务分解是将程序分解成适合并行执行的子任务。

子任务之间应该具有较小的计算量和较少的通信开销,以确保并行执行的效率。

任务调度是将子任务分配到不同的处理核心上进行执行。

任务调度的策略可以根据需求和优化的目标灵活选择,如负载均衡、最小化通信开销、最小化执行时间等。

并行程序设计中还需要解决通信和同步的问题。

在多核计算系统中,不同核心之间需要进行数据共享和通信。

通信的实现可以通过内存共享或消息传递来实现。

在进行数据共享和通信时,需要涉及同步机制来保证数据的一致性和正确性。

常用的同步机制有锁和信号量等。

并行程序设计的实现需要考虑编程语言和工具的选择。

目前,有许多编程语言和工具可以用于并行程序设计,如C/C++、Java、OpenMP、MPI等。

适合的编程语言和工具可以简化并行程序设计的复杂性,提高开发效率。

在并行程序设计的过程中,还需要进行性能分析和调优。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

多核编程与并行计算实验报告姓名:日期:2014年 4月20日实验一// exa1.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<process.h>#include<iostream>#include<fstream>using namespace std;void ThreadFunc1(PVOID param){while(1){Sleep(1000);cout<<"This is ThreadFunc1"<<endl;}}void ThreadFunc2(PVOID param){while(1){Sleep(1000);cout<<"This is ThreadFunc2"<<endl;}}int main(){int i=0;_beginthread(ThreadFunc1,0,NULL);_beginthread(ThreadFunc2,0,NULL);Sleep(3000);cout<<"end"<<endl;return 0;}实验二// exa2.cpp : Defines the entry point for the console application. //#include"stdafx.h"#include<windows.h>#include<iostream>using namespace std;DWORD WINAPI FunOne(LPVOID param){while(true){Sleep(1000);cout<<"hello! ";}return 0;}DWORD WINAPI FunTwo(LPVOID param){while(true){Sleep(1000);cout<<"world! ";}return 0;}int main(int argc, char* argv[]){int input=0;HANDLE hand1=CreateThread (NULL, 0, FunOne, (void*)&input, CREATE_SUSPENDED, NULL); HANDLE hand2=CreateThread (NULL, 0, FunTwo, (void*)&input, CREATE_SUSPENDED, NULL);while(true){cin>>input;if(input==1){ResumeThread(hand1);ResumeThread(hand2);}else{SuspendThread(hand1);SuspendThread(hand2);}};TerminateThread(hand1,1);TerminateThread(hand2,1);return 0;}实验三// exa3.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream>using namespace std;int globalvar = false;DWORD WINAPI ThreadFunc(LPVOID pParam){cout<<"ThreadFunc"<<endl;Sleep(200);globalvar = true;return 0;}int main(){HANDLE hthread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);if (!hthread){cout<<"Thread Create Error ! "<<endl;CloseHandle(hthread);}while (!globalvar)cout<<"Thread while"<<endl;cout<<"Thread exit"<<endl;return 0;}实验四:// exa4.cpp : Defines the entry point for the console application. //#include"stdafx.h"#include<windows.h>#include<process.h>#include<iostream>#include<fstream>using namespace std;HANDLE evRead, evFinish;void ReadThread(LPVOID param){WaitForSingleObject (evRead ,INFINITE);cout<<"Reading"<<endl;SetEvent (evFinish);}void WriteThread(LPVOID param){cout<<"Writing"<<endl;SetEvent (evRead);}int main(int argc , char * argv[]){evRead = CreateEvent (NULL ,FALSE ,FALSE ,NULL) ;evFinish = CreateEvent (NULL ,FALSE ,FALSE ,NULL) ;_beginthread(ReadThread , 0 , NULL) ;_beginthread(WriteThread , 0 , NULL) ;WaitForSingleObject (evFinish,INFINITE) ;cout<<"The Program is End"<<endl;return 0 ;}实验五// exa5.cpp : Defines the entry point for the console application. //#include"stdafx.h"#include<windows.h>#include<process.h>#include<iostream>#include<fstream>using namespace std;int total = 100 ;HANDLE evFin[2] ;CRITICAL_SECTION cs ;void WithdrawThread1(LPVOID param){EnterCriticalSection(&cs) ;if ( total-90 >= 0){total -= 90 ;cout<<"You withdraw 90"<<endl;}elsecout<<"You do not have that much money"<<endl;LeaveCriticalSection(&cs) ;SetEvent (evFin[0]) ;}void WithdrawThread2(LPVOID param){EnterCriticalSection(&cs) ;if ( total-20 >= 0){total -= 20 ;cout<<"You withdraw 20"<<endl;}elsecout<<"You do not have that much money"<<endl;LeaveCriticalSection(&cs) ;LeaveCriticalSection(&cs) ;SetEvent (evFin[1]) ;}int main(int argc , char * argv[]){evFin[0] = CreateEvent (NULL,FALSE,FALSE,NULL) ;evFin[1] = CreateEvent (NULL,FALSE,FALSE,NULL) ;InitializeCriticalSection(&cs) ;_beginthread(WithdrawThread1 , 0 , NULL) ;_beginthread(WithdrawThread2 , 0 , NULL) ;WaitForMultipleObjects(2 ,evFin ,TRUE ,INFINITE) ;DeleteCriticalSection(&cs) ;cout<<total<<endl;return 0 ;}实验六:// exa6.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream.h>#define THREAD_INSTANCE_NUMBER 3LONG g_fResourceInUse = FALSE;LONG g_lCounter = 0;DWORD ThreadProc(void * pData) {int ThreadNumberTemp = (*(int*) pData);HANDLE hMutex;cout << "ThreadProc: " << ThreadNumberTemp << " is running!" << endl;if ((hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "Mutex.Test")) == NULL) { cout << "Open Mutex error!" << endl;}cout << "ThreadProc " << ThreadNumberTemp << " gets the mutex"<< endl;ReleaseMutex(hMutex);CloseHandle(hMutex);return 0;}int main(int argc, char* argv[]){int i;DWORD ID[THREAD_INSTANCE_NUMBER];HANDLE h[THREAD_INSTANCE_NUMBER];HANDLE hMutex;if ( (hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "Mutex.Test")) == NULL) { if ((hMutex = CreateMutex(NULL, FALSE, "Mutex.Test")) == NULL ) { cout << "Create Mutex error!" << endl;return 0;}}for (i=0;i<THREAD_INSTANCE_NUMBER;i++){h[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc,(void *)&ID[i],0,&(ID[i]));if (h[i] == NULL)cout << "CreateThread error" << ID[i] << endl;elsecout << "CreateThread: " << ID[i] << endl;}WaitForMultipleObjects(THREAD_INSTANCE_NUMBER,h,TRUE,INFINITE);cout << "Close the Mutex Handle! " << endl;CloseHandle(hMutex);return 0;}实验七// exa7.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<iostream.h>#define THREAD_INSTANCE_NUMBER 3DWORD foo(void * pData) {int ThreadNumberTemp = (*(int*) pData);HANDLE hSemaphore;cout << "foo: " << ThreadNumberTemp << " is running!" << endl;if ((hSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, "Semaphore.Test")) == NULL) {cout << "Open Semaphore error!" << endl;}cout << "foo " << ThreadNumberTemp << " gets the semaphore"<< endl;ReleaseSemaphore(hSemaphore, 1, NULL);CloseHandle(hSemaphore);return 0;}int main(int argc, char* argv[]){int i;DWORD ThreadID[THREAD_INSTANCE_NUMBER];HANDLE hThread[THREAD_INSTANCE_NUMBER];HANDLE hSemaphore;if ((hSemaphore = CreateSemaphore(NULL,0,1, "Semaphore.Test")) == NULL ) { cout << "Create Semaphore error!" << endl;return 0;}for (i=0;i<THREAD_INSTANCE_NUMBER;i++){hThread[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) foo,(void *)&ThreadID[i],0,&(ThreadID[i]));if (hThread[i] == NULL)cout << "CreateThread error" << ThreadID[i] << endl;elsecout << "CreateThread: " << ThreadID[i] << endl;}WaitForMultipleObjects(THREAD_INSTANCE_NUMBER,hThread,TRUE,INFINITE);cout << "Close the Semaphore Handle! " << endl;CloseHandle(hSemaphore);return 0;}实验八:// exa8.cpp : Defines the class behaviors for the application.//#include"stdafx.h"#include"exa8.h"#include"MainFrm.h"#include"exa8Doc.h"#include"exa8View.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif///////////////////////////////////////////////////////////////////////////// // CExa8AppBEGIN_MESSAGE_MAP(CExa8App, CWinApp)//{{AFX_MSG_MAP(CExa8App)ON_COMMAND(ID_APP_ABOUT, OnAppAbout)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSG_MAP// Standard file based document commandsON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)END_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CExa8App constructionCExa8App::CExa8App(){// TODO: add construction code here,// Place all significant initialization in InitInstance}/////////////////////////////////////////////////////////////////////////////// The one and only CExa8App objectCExa8App theApp;/////////////////////////////////////////////////////////////////////////////// CExa8App initializationBOOL CExa8App::InitInstance(){AfxEnableControlContainer();// Standard initialization// If you are not using these features and wish to reduce the size// of your final executable, you should remove from the following// the specific initialization routines you do not need.#ifdef _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL #elseEnable3dControlsStatic(); // Call this when linking to MFC statically#endif// Change the registry key under which our settings are stored.// TODO: You should modify this string to be something appropriate// such as the name of your company or organization.SetRegistryKey(_T("Local AppWizard-Generated Applications"));LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates// serve as the connection between documents, frame windows and views.CSingleDocTemplate* pDocTemplate;pDocTemplate = new CSingleDocTemplate(IDR_MAINFRAME,RUNTIME_CLASS(CExa8Doc),RUNTIME_CLASS(CMainFrame), // main SDI frame windowRUNTIME_CLASS(CExa8View));AddDocTemplate(pDocTemplate);// Parse command line for standard shell commands, DDE, file openCCommandLineInfo cmdInfo;ParseCommandLine(cmdInfo);// Dispatch commands specified on the command lineif (!ProcessShellCommand(cmdInfo))return FALSE;// The one and only window has been initialized, so show and update it.m_pMainWnd->ShowWindow(SW_SHOW);m_pMainWnd->UpdateWindow();return TRUE;}///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialog{public:CAboutDlg();// Dialog Data//{{AFX_DATA(CAboutDlg)enum { IDD = IDD_ABOUTBOX };//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAboutDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL// Implementationprotected://{{AFX_MSG(CAboutDlg)// No message handlers//}}AFX_MSGDECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){//{{AFX_DATA_INIT(CAboutDlg)//}}AFX_DATA_INIT}void CAboutDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAboutDlg)//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)// No message handlers//}}AFX_MSG_MAPEND_MESSAGE_MAP()// App command to run the dialogvoid CExa8App::OnAppAbout(){CAboutDlg aboutDlg;aboutDlg.DoModal();}///////////////////////////////////////////////////////////////////////////// // CExa8App message handlers、实验九:using System;using System.Threading;class Test{static void Main(){ThreadStart threadDelegate = new ThreadStart(Work.DoWork);Thread newThread = new Thread(threadDelegate);newThread.Start();Work w = new Work();w.Data = 42;threadDelegate = new ThreadStart(w.DoMoreWork);newThread = new Thread(threadDelegate);newThread.Start();}}class Work{public static void DoWork(){Console.WriteLine("Static thread procedure.");}public int Data;public void DoMoreWork(){Console.WriteLine("Instance thread procedure. Data={0}", Data);}实验十:using System;using System.Threading;class Test{static int total = 100;public static void WithDraw1(){int n=90;if (n <= total){total -= n;Console.WriteLine("You have withdrawn. n={0}", n);Console.WriteLine("total={0}", total);}else{Console.WriteLine("You do not enough money. n={0}", n);Console.WriteLine("total={0}", total);}}public static void WithDraw2()int n = 20;if (n <= total){total -= n;Console.WriteLine("You have withdrawn. n={0}", n);Console.WriteLine("total={0}", total);}else{Console.WriteLine("You do not enough money. n={0}", n);Console.WriteLine("total={0}", total);}}public static void Main(){ThreadStart thread1 = new ThreadStart(WithDraw1);Thread newThread1 = new Thread(thread1);ThreadStart thread2 = new ThreadStart(WithDraw2);Thread newThread2 = new Thread(thread2);newThread1.Start();newThread2.Start();}}实验十一:// exa11.cpp : Defines the entry point for the console application.//#include"stdafx.h"#include<windows.h>#include<conio.h>#include<stdio.h>#define THREAD_INSTANCE_NUMBER 3LONG g_fResourceInUse = FALSE;LONG g_lCounter = 0;CRITICAL_SECTION cs;DWORD ThreadProc1(void * pData) {int ThreadNumberTemp = (*(int*) pData);printf("ThreadProc1: %d is running!\n",ThreadNumberTemp );EnterCriticalSection(&cs);printf("ThreadProc1 %d enters into critical section\n",ThreadNumberTemp);Sleep(1000);LeaveCriticalSection(&cs);return 0;}DWORD ThreadProc2(void * pData) {int ThreadNumberTemp = (*(int*) pData);printf("ThreadProc2: %d is running!\n",ThreadNumberTemp );EnterCriticalSection(&cs);printf("ThreadProc2 %d enters into critical section\n",ThreadNumberTemp);Sleep(1000);LeaveCriticalSection(&cs);return 0;}int main(int argc, char* argv[]){int i;DWORD ID1,ID2;HANDLE h1,h2;InitializeCriticalSection(&cs);printf("Create the critical section \n");h1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc1,(void *)&ID1,0,&(ID1));if (h1 == NULL)printf("CreateThread error %d \n",ID1);elseprintf("CreateThread %d \n",ID1);h2= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc2,(void *)&ID2,0,&(ID2));if (h2== NULL)printf("CreateThread error %d \n",ID2);elseprintf("CreateThread %d \n",ID2);WaitForSingleObject (h1,INFINITE);WaitForSingleObject (h2,INFINITE);printf("Delete the critical section \n");DeleteCriticalSection(&cs);getch();return 0;}。

相关文档
最新文档