简单的多线程练习两例

来源:互联网 发布:cad软件安装教程 编辑:程序博客网 时间:2024/06/01 13:23

例1:在主线程(main)中创建一个子线程,判断7s超时。

#include <iostream>#include <time.h> #include <windows.h>using namespace std;DWORD WINAPI timeOutTest(LPVOID lpParamter){         clock_t start, finish;   double duration;    start=clock();       while(1)    {   finish = clock();  duration = (double)(finish - start) / CLOCKS_PER_SEC;   cout<<"Time duration: "<<duration<<endl;   if(duration>=7.0)  break;        }   return 0;}int main(){      HANDLE hThread = CreateThread(NULL, 0, timeOutTest, NULL, 0, NULL);      CloseHandle(hThread);      while(1)  {}      return 0;}
结果:


例2:含有互斥变量的简单多线程。

main和Fun互斥访问{WaitForSingleObject.....ReleaseMutex}之间的变量。

#include <iostream>#include <windows.h>using namespace std;int x=0;HANDLE hMutex;DWORD WINAPI Fun(LPVOID lpParamter){             while(1)    {                  WaitForSingleObject(hMutex, INFINITE);         //        cout<<"Fun display!"<<endl;  x=x+1; cout<<"Fun x: "<<x<<endl;                 Sleep(1000);                 ReleaseMutex(hMutex);        }}int main(){      HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);      hMutex = CreateMutex(NULL, FALSE, "screen");      CloseHandle(hThread);      while(1)   {               WaitForSingleObject(hMutex, INFINITE);            //   cout<<"main display!"<<endl;     x=x+1;   cout<<"Main x: "<<x<<endl;               Sleep(2000);               ReleaseMutex(hMutex);      }      return 0;}

相关blog:C++多线程编程简单实例



原创粉丝点击