C++ 多线程编程实例

来源:互联网 发布:什么是人工智能英文 编辑:程序博客网 时间:2024/05/02 06:09
   

创建线程的函数

HANDLE CreateThread( 

    LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD

    SIZE_T dwStackSize,                       // initial stack size

    LPTHREAD_START_ROUTINE lpStartAddress,    // thread function

    LPVOID lpParameter,                       // thread argument

    DWORD dwCreationFlags,                    // creation option

    LPDWORD lpThreadId                        // thread identifier

);

在这里我们只用到了第三个和第四个参数,第三个参数传递了一个函数的地址,也是我们要指定的新的线程第四个参数是传给新线程的参数指针。

从网上搜集来的非常基础的C++多线程实例,刚入门的可以看看,希望能有所帮助。
Cpp代码 
  1. //这是2个线程模拟卖火车票的小程序   
  2. #include <windows.h>   
  3. #include <iostream.h>   
  4.   
  5. DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread data   
  6. DWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread data   
  7.   
  8. int index=0;   
  9. int tickets=10;   
  10. HANDLE hMutex;   
  11. void main()   
  12. {   
  13.     HANDLE hThread1;   
  14.     HANDLE hThread2;   
  15.     //创建线程   
  16.   
  17.     hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);   
  18.     hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);   
  19.     CloseHandle(hThread1);   
  20.     CloseHandle(hThread2);   
  21.   
  22.     //创建互斥对象   
  23.     hMutex=CreateMutex(NULL,TRUE,"tickets");   
  24.     if (hMutex)   
  25.     {   
  26.         if (ERROR_ALREADY_EXISTS==GetLastError())   
  27.         {   
  28.             cout<<"only one instance can run!"<<endl;   
  29.             return;   
  30.         }   
  31.     }   
  32.     WaitForSingleObject(hMutex,INFINITE);   
  33.     ReleaseMutex(hMutex);   
  34.     ReleaseMutex(hMutex);   
  35.        
  36.     Sleep(4000);   
  37. }   
  38. //线程1的入口函数   
  39. DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data   
  40. {   
  41.     while (true)   
  42.     {   
  43.         ReleaseMutex(hMutex);   
  44.         WaitForSingleObject(hMutex,INFINITE);   
  45.         if (tickets>0)   
  46.         {   
  47.             Sleep(1);   
  48.             cout<<"thread1 sell ticket :"<<tickets--<<endl;   
  49.         }   
  50.         else  
  51.             break;   
  52.         ReleaseMutex(hMutex);   
  53.     }   
  54.   
  55.     return 0;   
  56. }   
  57. //线程2的入口函数   
  58. DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data   
  59. {   
  60.     while (true)   
  61.     {   
  62.         ReleaseMutex(hMutex);   
  63.         WaitForSingleObject(hMutex,INFINITE);   
  64.         if (tickets>0)   
  65.         {   
  66.             Sleep(1);   
  67.             cout<<"thread2 sell ticket :"<<tickets--<<endl;   
  68.         }   
  69.         else  
  70.             break;   
  71.         ReleaseMutex(hMutex);   
  72.     }   
  73.        
  74.     return 0;   
  75. }  
0 0
原创粉丝点击