临界区 互斥体 测试代码

2017-04-20  本文已影响16人  Fa1se003

临界区

#include "stdafx.h"
#include <windows.h>

int total = 100;
CRITICAL_SECTION cs;

DWORD WINAPI test1(LPVOID param)
{
        bool isRun = true;
        while(isRun)
        {
                EnterCriticalSection(&cs);
                if(total>0)
                {
                        printf("线程test1工作中=====还剩%d张票\n",total);
                        total--;
                        printf("卖出一张,还剩%d张票\n",total);
                }
                else
                {
                        isRun = false;
                }
                LeaveCriticalSection(&cs);
        }

        return 0;
}



DWORD WINAPI test2(LPVOID param)
{
        bool isRun = true;
        while(isRun)
        {        
                EnterCriticalSection(&cs);
                if(total>0)
                {
                        printf("线程test2工作中=====还剩%d张票\n",total);
                        total--;
                        printf("卖出一张,还剩%d张票\n",total);
                }
                else
                {
                        isRun = false;
                }

                LeaveCriticalSection(&cs);
        }
        return 0;
}



int main(int argc, char* argv[])
{
        HANDLE hThread[2];
        InitializeCriticalSection(&cs);

        hThread[0] = CreateThread(NULL,0,test1,NULL,0,NULL);
        hThread[1] = CreateThread(NULL,0,test2,NULL,0,NULL);
        WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
        CloseHandle(hThread[0]);
        CloseHandle(hThread[1]);

        printf("Hello World!\n");
        return 0;
}

互斥体

#include "stdafx.h"
#include "windows.h"
 
int main(int argc, char* argv[])
{
    //创建互斥体
    HANDLE m_hMutex = CreateMutex(NULL,FALSE,"cplusplus_me");
    /*
        m_hMutex创建成功返回句柄,如果已经存在返回已经存在的句柄,
        GetLastError 返回  ERROR_ALREADY_EXISTS
    */

    WaitForSingleObject(m_hMutex,INFINITE);//获取令牌
    DWORD dwRet = GetLastError();
    if (m_hMutex)
    {
        if (ERROR_ALREADY_EXISTS == dwRet)//防止多开的一种手段
        {
            printf("程序已经在运行中了,程序退出!\n");
            CloseHandle(m_hMutex);
            return 0;
        }
    }
    else
    {
        printf("创建互斥量错误,程序退出!\n");
        CloseHandle(m_hMutex);
        return 0;
    }
    while(1)
    {
        printf("cplusplus_me\n");
    }

    ReleaseMutex(m_hMutex);//释放令牌
    CloseHandle(m_hMutex);
    return 0;
}

想知道CreateMutex的第二个参数的朋友,自己查下文档。

上一篇下一篇

猜你喜欢

热点阅读