C++多线程

一 简单实例
比较简单的代码,创建10个线程,其中使第4个线程在一创建就挂起,等到其他的线程执行的差不多的时候再使第4个线程恢复执行。

 

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <windows.h>   
  4. #define THREAD_NUM 10  
  5.    
  6. DWORD WINAPI PrintThreads (LPVOID);  
  7.    
  8. int main ()   
  9. {   
  10.     HANDLE hThread[THREAD_NUM];   
  11.     DWORD dwThreadID[THREAD_NUM];   
  12.    
  13.     for (int i=0; i<THREAD_NUM; ++i)   
  14.     {   
  15.         int isStartImmediate = 0;  
  16.         if(3 == i)  
  17.         isStartImmediate = CREATE_SUSPENDED;  
  18.         hThread[i]=CreateThread(NULL,     
  19.             0,    
  20.             PrintThreads,     
  21.             (LPVOID)i,    
  22.             isStartImmediate,     
  23.             &dwThreadID[i]);   
  24.         if (hThread[i])  
  25.         {   
  26.             printf ("Thread launched successfully/n");                  
  27.         }           
  28.     }   
  29.     printf("Start sleep 100, and let other thread excute/n");  
  30.     Sleep (100);      
  31.   
  32.     printf("Start sleep 100, and thread 3 excute/n");  
  33.     ResumeThread(hThread[3]);  
  34.   
  35.     Sleep(100);  
  36.       
  37.     for(int i = 0; i<THREAD_NUM; ++i)  
  38.     {  
  39.         if (hThread[i])  
  40.         {        
  41.             // You need to use this to release kernel objects   
  42.             //when you are done using them.   
  43.             // If a process exits without closing the thread handle,   
  44.             // the operating system drops the reference counts for those objects.   
  45.             // But if a process frequently creates threads without closing the handles,   
  46.             // there could be hundreds of thread kernel objects lying around and these   
  47.             //resource leaks can have a big hit on performance.  
  48.             CloseHandle(hThread[i]);      
  49.         }   
  50.     }  
  51.     return (0);   
  52. }   
  53.    
  54. //function PrintThreads   
  55. DWORD WINAPI PrintThreads (LPVOID num)  
  56. {  
  57.     for (int i=0; i<10; i++)   
  58.     printf ("Thread Number is %d%d%d/n", num,num,num);   
  59.     return 0;  

MSDN中CreateThread原型:

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
);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值