Windows Event 的各個相關函數解釋 及 簡單例子一個


SetEvent 是設置信號為 有信號狀態
ReSetEvent 是設置信號為 無信號狀態
CreateEvent的第二個參數如果是TRUE,意思是你必須用SetEvent和ResetEvent來設置信號,如果為FALSE,則用WaitForSingleObject自動進入無信號狀態。結束后用SetEvent重置為信號狀態。

OpenEvent可以打開一個先前已經創建好的Event,只要名字對,就可以打開該event。

Event事件分 人工事件和自動事件。
當使用人工事件方式時,需要手動設置ResetEvent 為無信號狀態,及表示資源被占用中。當釋放資源時,用SetEvent 設置為有信號狀態。
當使用自動事件方式時,系統默認將ResetEvent 設置為無信號狀態,最后釋放資源時用SetEvent設置為有信號狀態。
 
 
 
 
以下有2個進程,A和B,其中A可以決定一個event的狀態(要么set,要么reset),而B中有一個循環不停去讀該event(waitforsingleobject()函數),並給出輸出提示當前event的狀態是什么。
//a.cpp
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
    int i = 0;
    CHAR a[20] = "RIX";                                    //event name
    LPCSTR str = a;                                        //event name
    HANDLE handle = CreateEvent(NULL, TRUE, TRUE, str);    //create a event

    while(1)
    {
        cout<<"Press 1 to set event,";
        cout<<" 2 to reset event,";
        cout<<" 5 to shut down..."<<endl;
        cin>>i;                                            //read command is a while(1) looop
        if (i == 1)                                        //to set event
        {
            if (SetEvent(handle))
                cout<<"SetEvent() completed!"<<endl;
            else
                cout<<"SetEvent() err!!"<<endl;
        }
        else if (i == 2)                                //to reset event
        {
            if (ResetEvent(handle))
                cout<<"ResetEvent() completed!"<<endl;
            else
                cout<<"ResetEvent() err!!"<<endl;
        }
        else if (i==0)                                    //break
        {
            cout<<"going to shut down..."<<endl;
            break;
        }
    }
    return 1;
}

 

//b.cpp
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
    LPCSTR a = "RIX";
    HANDLE handle = OpenEvent(EVENT_ALL_ACCESS, FALSE, a);
    DWORD b = 22;
    while(1)
    {
        Sleep(1000);
        b = WaitForSingleObject(handle, 1);                    //check event value
        if (b == 0)                                            //if event is set!! b can do something
        {
            cout<<"Got event!!!!!!!!! We can do something!"<<endl<<endl;
        }
        else                                                //if event is not set, waitforsingleobject is timeout... 
        {
            cout<<"Timeout........... b = "<<b<<endl<<endl;
        }
    }
    
}

 

 我們運行一下,

首先創建一個set的event,然后點2改為reset,然后再點1改為set,看process A 和 process B的結果:

A process:

 

B process:

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM