MFC 多線程訪問同一個變量之互斥鎖(CSingleLock )


先來一個例子:

一個進程開兩個線程,這兩個線程修改一個變量,並把這個變量的值打印出來

 

以下是代碼(VS2010):

新建一個解決方案:MutexTest

 

 

 

修改MutexTestDlg.h

// MutexTestDlg.h : header file
//

#pragma once

#include <Windows.h>


// CMutexTestDlg dialog
class CMutexTestDlg : public CDialogEx
{
// Construction
public:
	CMutexTestDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	enum { IDD = IDD_MUTEXTEST_DIALOG };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support


	int m_nCount;
	CString m_strCount;
	BOOL	m_bKillThread;

	static UINT MyThread1(LPVOID* pParam);//thread1 function
	CWinThread *Thread1;//thread1

	static UINT MyThread2(LPVOID* pParam);//thread2 function
	CWinThread *Thread2;//thread2



// Implementation
protected:
	HICON m_hIcon;

	// Generated message map functions
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnBnClickedButton1();
	afx_msg void OnBnClickedButton2();
	afx_msg void OnBnClickedButton3();
	afx_msg void OnBnClickedButton4();
};

  

修改MutexTestDlg.cpp

// MutexTestDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MutexTest.h"
#include "MutexTestDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif



// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CMutexTestDlg dialog

CMutexTestDlg::CMutexTestDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CMutexTestDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_nCount = 0;
	m_strCount = "";
	m_bKillThread = FALSE;
}

void CMutexTestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CMutexTestDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, &CMutexTestDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CMutexTestDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CMutexTestDlg::OnBnClickedButton3)
	ON_BN_CLICKED(IDC_BUTTON4, &CMutexTestDlg::OnBnClickedButton4)
END_MESSAGE_MAP()


// CMutexTestDlg message handlers

BOOL CMutexTestDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMutexTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMutexTestDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMutexTestDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



UINT CMutexTestDlg::MyThread1(LPVOID* pParam)
{

	CMutexTestDlg * pMutexTestDlg= (CMutexTestDlg *)pParam;
	while(1)
	{	
		if(pMutexTestDlg->m_bKillThread)
		{
			DWORD dwExitCode;
			GetExitCodeThread(pMutexTestDlg->Thread1, &dwExitCode);
			AfxEndThread(dwExitCode, TRUE);
		}
		else
		{
			pMutexTestDlg->m_nCount = 1;
			pMutexTestDlg->m_strCount.Format(_T("%d"), pMutexTestDlg->m_nCount);
			pMutexTestDlg->SetDlgItemText(IDC_EDIT1, pMutexTestDlg->m_strCount);
			Sleep(300);
		}
		
	}	return 0;
}


UINT CMutexTestDlg::MyThread2(LPVOID* pParam)
{

	CMutexTestDlg * pMutexTestDlg= (CMutexTestDlg *)pParam;
	while(1)
	{	
		if(pMutexTestDlg->m_bKillThread)
		{
			DWORD dwExitCode;
			GetExitCodeThread(pMutexTestDlg->Thread2, &dwExitCode);
			AfxEndThread(dwExitCode, TRUE);
		}
		else
		{
			pMutexTestDlg->m_nCount = 2;
			pMutexTestDlg->m_strCount.Format(_T("%d"), pMutexTestDlg->m_nCount);
			pMutexTestDlg->SetDlgItemText(IDC_EDIT2, pMutexTestDlg->m_strCount);
			Sleep(300);
		}
		
	}	return 0;
}


void CMutexTestDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
	Thread1 = AfxBeginThread((AFX_THREADPROC)MyThread1, this);	//Start thread
	Thread2 = AfxBeginThread((AFX_THREADPROC)MyThread2, this);	//Start thread

	m_bKillThread = FALSE;
}


void CMutexTestDlg::OnBnClickedButton2()
{
	// TODO: Add your control notification handler code here
	Thread1->SuspendThread();	//Pause thread
	Thread2->SuspendThread();	//Pause thread
}


void CMutexTestDlg::OnBnClickedButton3()
{
	// TODO: Add your control notification handler code here
	Thread1->ResumeThread();	//Continue
	Thread2->ResumeThread();	//Continue
}


void CMutexTestDlg::OnBnClickedButton4()
{
	// TODO: Add your control notification handler code here
	m_bKillThread = TRUE;
	Thread1->ResumeThread();	//Continue thread run (if thread is suspend, end thread will failed.)
	Thread2->ResumeThread();	//Continue thread run (if thread is suspend, end thread will failed.)
}

  

編譯-運行,點擊【Start】按鈕后,【Pause】和【Continue】互相切換點擊, 會發現這兩個編輯框會顯示相同的值,並不是代碼中寫的第一個編輯框設置1,第二個編輯框設置2

 

 以上的原因時因為兩個線程修改設置同一個變量,導致一個線程准備顯示值得時候,被另一個線程修改了,導致兩個編輯框顯示的值一致

 

解決辦法就是加互斥鎖Mutex

 

將代碼做如下修改:

1.在MutexTestDlg.cpp中加入全局類變量  CMutex Mutex;

2.在兩個線程中定義互斥鎖類變量 CSingleLock singleLock(&Mutex);

3.把在線程中需要保護的代碼保護起來

singleLock.Lock();
if (singleLock.IsLocked()) 
{
  //需要保護的變量
}
singleLock.Unlock();

 

修改后的Cpp如下:

 

// MutexTestDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MutexTest.h"
#include "MutexTestDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


CMutex Mutex;  //mutex


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
    CAboutDlg();

// Dialog Data
    enum { IDD = IDD_ABOUTBOX };

    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CMutexTestDlg dialog

CMutexTestDlg::CMutexTestDlg(CWnd* pParent /*=NULL*/)
    : CDialogEx(CMutexTestDlg::IDD, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
    m_nCount = 0;
    m_strCount = "";
    m_bKillThread = FALSE;
}

void CMutexTestDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CMutexTestDlg, CDialogEx)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDC_BUTTON1, &CMutexTestDlg::OnBnClickedButton1)
    ON_BN_CLICKED(IDC_BUTTON2, &CMutexTestDlg::OnBnClickedButton2)
    ON_BN_CLICKED(IDC_BUTTON3, &CMutexTestDlg::OnBnClickedButton3)
    ON_BN_CLICKED(IDC_BUTTON4, &CMutexTestDlg::OnBnClickedButton4)
END_MESSAGE_MAP()


// CMutexTestDlg message handlers

BOOL CMutexTestDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);            // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon

    // TODO: Add extra initialization here

    return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMutexTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialogEx::OnSysCommand(nID, lParam);
    }
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMutexTestDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;

        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialogEx::OnPaint();
    }
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMutexTestDlg::OnQueryDragIcon()
{
    return static_cast<HCURSOR>(m_hIcon);
}



UINT CMutexTestDlg::MyThread1(LPVOID* pParam)
{
    CSingleLock singleLock(&Mutex);  //Mutex

    CMutexTestDlg * pMutexTestDlg= (CMutexTestDlg *)pParam;
    while(1)
    {    
        if(pMutexTestDlg->m_bKillThread)
        {
            DWORD dwExitCode;
            GetExitCodeThread(pMutexTestDlg->Thread1, &dwExitCode);
            AfxEndThread(dwExitCode, TRUE);
        }
        else
        {
            singleLock.Lock();      //Mutex   
      if (singleLock.IsLocked()) {
                pMutexTestDlg->m_nCount = 1;
                pMutexTestDlg->m_strCount.Format(_T("%d"), pMutexTestDlg->m_nCount);
                pMutexTestDlg->SetDlgItemText(IDC_EDIT1, pMutexTestDlg->m_strCount);
                Sleep(300);
           singleLock.Unlock();  //Mutex
 }        
        }
        
    }    return 0;
}


UINT CMutexTestDlg::MyThread2(LPVOID* pParam)
{
    CSingleLock singleLock(&Mutex);  //mutex

    CMutexTestDlg * pMutexTestDlg= (CMutexTestDlg *)pParam;
    while(1)
    {    
        if(pMutexTestDlg->m_bKillThread)
        {
            DWORD dwExitCode;
            GetExitCodeThread(pMutexTestDlg->Thread2, &dwExitCode);
            AfxEndThread(dwExitCode, TRUE);
        }
        else
        {
            singleLock.Lock();  //mutex
            if (singleLock.IsLocked())  //mutex
 {
                pMutexTestDlg->m_nCount = 2;
                pMutexTestDlg->m_strCount.Format(_T("%d"), pMutexTestDlg->m_nCount);
                pMutexTestDlg->SetDlgItemText(IDC_EDIT2, pMutexTestDlg->m_strCount);
                Sleep(300);
        singleLock.Unlock();  //mutex
 }
        }
        
    }    return 0;
}


void CMutexTestDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    Thread1 = AfxBeginThread((AFX_THREADPROC)MyThread1, this);    //Start thread
    Thread2 = AfxBeginThread((AFX_THREADPROC)MyThread2, this);    //Start thread

    m_bKillThread = FALSE;
}


void CMutexTestDlg::OnBnClickedButton2()
{
    // TODO: Add your control notification handler code here
    Thread1->SuspendThread();    //Pause thread
    Thread2->SuspendThread();    //Pause thread
}


void CMutexTestDlg::OnBnClickedButton3()
{
    // TODO: Add your control notification handler code here
    Thread1->ResumeThread();    //Continue
    Thread2->ResumeThread();    //Continue
}


void CMutexTestDlg::OnBnClickedButton4()
{
    // TODO: Add your control notification handler code here
    m_bKillThread = TRUE;
    Thread1->ResumeThread();    //Continue thread run (if thread is suspend, end thread will failed.)
    Thread2->ResumeThread();    //Continue thread run (if thread is suspend, end thread will failed.)
}

 

  之后就可以正常運行了

 

 【注意】:多線程涉及訪問修改同一變量,一定要加🔒進行保護。

 

擴展知識:臨界區也可以實現以上的功能,區別在於臨界區速度快,只可用於進程中的多個線程,

互斥量可以防止多個進程對共享數據的同時修改操作。

另外,用 WaitForSingleObject 和 ReleaseMutex也可以


免責聲明!

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



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