(此文档为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;}。