线程同步的一些方法

信号量、Event、互斥变量mutex、临界区

一、信号量



#include <windows.h> 
#include <stdio.h>  
#define MAX_SEM_COUNT 6 
#define THREADCOUNT 12  
HANDLE ghSemaphore;  
DWORD WINAPI ThreadProc( LPVOID );  
void main() {     
HANDLE aThread[THREADCOUNT];     
DWORD ThreadID;     int i;      
// Create a semaphore with initial and max counts of MAX_SEM_COUNT      
ghSemaphore = CreateSemaphore(          NULL,           
// default security attributes         
MAX_SEM_COUNT,  
// initial count         
MAX_SEM_COUNT,  
// maximum count         
NULL);          
// unnamed semaphore      
if (ghSemaphore == NULL)      
{         
printf("CreateSemaphore error: %d/n", GetLastError());         
return;     
}      
// Create worker threads      
for( i=0; i < THREADCOUNT; i++ )     
{         
aThread[i] = CreateThread(                       
NULL, // default security attributes                      
0,          // default stack size                      
(LPTHREAD_START_ROUTINE) ThreadProc,                      
NULL,       // no thread function arguments                      
0,          // default creation flags                      
&ThreadID); // receive thread identifier          
if( aThread[i] == NULL )        
{             
printf("CreateThread error: %d/n", GetLastError());             
return;         
}     
}      // Wait for all threads to terminate      
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);      
// Close thread and semaphore handles      
for( i=0; i < THREADCOUNT; i++ )         
CloseHandle(aThread[i]);      
CloseHandle(ghSemaphore); 
}  
DWORD WINAPI ThreadProc( LPVOID lpParam )
{     
DWORD dwWaitResult;      
BOOL bContinue=TRUE;      
while(bContinue)     
{         // Try to enter the semaphore gate.          
dwWaitResult = WaitForSingleObject(              ghSemaphore,   // handle to semaphore             
3L);           // zero-second time-out interval          
switch (dwWaitResult)          {              // The semaphore object was signaled.             
case WAIT_OBJECT_0:                  // TODO: Perform task                 
printf("Thread %d: wait succeeded/n", GetCurrentThreadId());                 
bContinue=FALSE;                              // Simulate thread spending time on task                 
Sleep(5);                  
for(int x = 0; x< 10; x++)                     
printf("Thread %d task!/n",GetCurrentThreadId());                  
// Relase the semaphore when task is finished                  
if (!ReleaseSemaphore(                          ghSemaphore,  
// handle to semaphore                         
1,            // increase count by one                         
NULL) )       // not interested in previous count                 
{                     
printf("ReleaseSemaphore error: %d/n", GetLastError());                
}                 
break;              
// The semaphore was nonsignaled, so a time-out occurred.             
case WAIT_TIMEOUT:                  
printf("Thread %d: wait timed out/n", GetCurrentThreadId());                 
break;          
}     
}     
return TRUE; 
}


二、Event

// CreatEventDemo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;
DWORD WINAPI ThreadProc1(LPVOID lpParam);
DWORD WINAPI ThreadProc2(LPVOID lpParam);
HANDLE hEvent = NULL;
HANDLE hThread1 = NULL;
HANDLE hThread2 = NULL;
int main(int argc,char *args[])
{
hEvent = CreateEvent(NULL,TRUE,TRUE,NULL); //使用手动重置为无信号状态,初始化时有信号状态
hThread1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc1,NULL,0,NULL);
Sleep(200);
hThread2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc2,NULL,0,NULL);
Sleep(200);
if (NULL == hThread1 || NULL == hThread2)
{
cout <<"create thread fail!";
}
//DWORD dCount = ResumeThread(hThread);
return 0;
}
DWORD WINAPI ThreadProc1(LPVOID lpParam)
{
cout <<"in thread1@!"<<endl;
DWORD dReturn = WaitForSingleObject(hEvent,INFINITE);
if (WAIT_OBJECT_0 == dReturn)
{
cout <<" thread1 signaled ! "<<endl;
}
cout <<"in thread1 --signal"<<endl;
//SetEvent(hEvent);
return 0;
}
DWORD WINAPI ThreadProc2(LPVOID lpParam)
{
cout <<"in thread2@!"<<endl;
DWORD dReturn = WaitForSingleObject(hEvent,INFINITE);
if (WAIT_OBJECT_0 == dReturn)
{
cout <<"thread2 signaled ! "<<endl;
}
cout <<"in thread2--signal"<<endl;
return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值