1. 程式人生 > >C++ 普通鎖和獨特鎖的使用

C++ 普通鎖和獨特鎖的使用

Manager.h標頭檔案

如果沒有鎖,那麼A和B執行緒將會交替執行;有了鎖後,那麼就會先執行A,再到B

#pragma once

#include <mutex>
#include <thread>
#include <windows.h>

using namespace std;

class CManager
{
public:
    CManager();
    ~CManager();

public:
    void Start();

private:
    void AFunction();
    void BFunction();

private
: mutex counter_mutex; };

Manager.cpp原始檔

#include "stdafx.h"
#include "Manager.h"

CManager::CManager()
{

}


CManager::~CManager()
{
}

void CManager::Start()
{
    thread threadA(&CManager::AFunction, this);
    thread threadB(&CManager::BFunction, this);

    threadA.detach();
    threadB.detach();

    printf
("This is the main Thread...\n"); } void CManager::AFunction() { //終止程序// //ExitThread(GetCurrentThreadId()); counter_mutex.lock(); for (int i=0;i<50;i++) { Sleep(100); printf("AFunction...%d\n",i); } counter_mutex.unlock(); } void CManager::BFunction() { counter_mutex.lock(); for
(int i = 0; i < 50; i++) { Sleep(100); printf("BFunction...%d\n", i); } counter_mutex.unlock(); }

UniqueManager.h

#pragma once

#include <mutex>
#include <thread>
#include <windows.h>

using namespace std;

class CUniqueManager
{
public:
CUniqueManager();
~CUniqueManager();

public:
void Start();

private:
void AFunction();
void BFunction();

private:
mutex counter_mutex;
};

uniqueManager.cpp

#include "stdafx.h"
#include "UniqueManager.h"


CUniqueManager::CUniqueManager()
{
}


CUniqueManager::~CUniqueManager()
{
}

void CUniqueManager::Start()
{
    thread threadA(&CUniqueManager::AFunction, this);
    thread threadB(&CUniqueManager::BFunction, this);

    threadA.detach();
    threadB.detach();

    printf("This is the main Thread...\n");
}

void CUniqueManager::AFunction()
{
    unique_lock<mutex> lck(counter_mutex);
    for (int i = 0; i < 50; i++)
    {
        Sleep(100);
        printf("AFunction...%d\n", i);
    }
}

void CUniqueManager::BFunction()
{
    unique_lock<mutex> lck(counter_mutex);
    for (int i = 0; i < 50; i++)
    {
        Sleep(100);
        printf("BFunction...%d\n", i);
    }
}

主程式

#include "stdafx.h"
#include "Manager.h"
int main()
{
    CManager *manager = new CManager();

    manager->Start();

    getchar();

    delete manager;
    manager = NULL;

    return 0;
}