1. 程式人生 > >vc 多執行緒處理臨界資料,

vc 多執行緒處理臨界資料,

#include <iostream>
#include <Windows.h>
using namespace std;
int sum = 100;
DWORD WINAPI threadfun(LPVOID lpParameter);
int temp =1;
HANDLE m_mutex;
HANDLE handle1;
HANDLE handle2;
HANDLE handle3;
HANDLE handle4;
CRITICAL_SECTION g_cs;
int main()
{
    char pmsg1[10] = "hello_1\n";
    char pmsg2[10] = "hello_2\n";
    char pmsg3[10] = "hello_3\n";
    char pmsg4[10] = "hello_4\n";
    // m_mutex = ::CreateMutex(NULL, FALSE, NULL);
    // if(!m_mutex)cout<<"CreateMutex fail"<<endl;
     handle1 = CreateThread(NULL,0,threadfun,(void*)pmsg1,0,NULL);
     handle2 = CreateThread(NULL,0,threadfun,(void*)pmsg1,0,NULL);
     handle3 = CreateThread(NULL,0,threadfun,(void*)pmsg1,0,NULL);
     handle4 = CreateThread(NULL,0,threadfun,(void*)pmsg1,0,NULL);

    CloseHandle(handle1);
    CloseHandle(handle2);
    CloseHandle(handle3);
    CloseHandle(handle4);
//    ::CloseHandle(m_mutex);

    getchar();
    return 0;
}

void sumSub()
{
        InitializeCriticalSection(&g_cs);
        Sleep(2);
    while(sum > 0)
    {    
        EnterCriticalSection(&g_cs);
        cout << "tid: " << GetCurrentThreadId() << "\tsum: " << sum-- << endl;
        LeaveCriticalSection(&g_cs);
        Sleep(3);
        
    }

}
DWORD WINAPI threadfun(LPVOID lpParameter)
{
    /*char* pmsg = (char*)lpParameter;
    cout<<pmsg;*/

    sumSub();
    return 0;
}