MFC中关于CMutex类的学习

MFC中关于CMutex类的学习

最近在项目中要实现两个线程之间的同步,MFC中提供了4个类,分别是CMutex(互斥量)、CCriticalSection(临界区)、CEvent(事件对象)、CSemaphore(信号量)。有关这4个类的说明,大家可以参考微软官方文档:

CMutex 类 | Microsoft Learn

CEvent 类 | Microsoft Learn

CCriticalSection 类 | Microsoft Learn

CSemaphore 类 | Microsoft Learn

今天我们要用到的是CMutex类。下面我们用一个简单的实力来介绍:

新建一个控制台应用程序如下图:

并且添加如下代码

复制代码
#include <iostream>
#include <afxmt.h>
#include <thread>
#include <afxwin.h>
using namespace std;

CMutex g_Mutex;

int g_Count = 0;

void PrintfOddNum()
{
	while (g_Count < 100)
	{
		g_Mutex.Lock();
		//CSingleLock lock(&g_Mutex);
		if (g_Count % 2 == 1)
		{
			cout << "thr1:" << g_Count << endl;
			g_Count++;
		}
		//lock.Unlock();
		g_Mutex.Unlock();
	}
}

void PrintfEvenNum()
{
	while (g_Count < 100)
	{
		g_Mutex.Lock();
		//CSingleLock lock(&g_Mutex);
		if (g_Count % 2 == 0)
		{
			cout << "thr2:" << g_Count << endl;
			g_Count++;
		}
		//lock.Unlock();
		g_Mutex.Unlock();
	}
}

int main()
{
	thread th1(PrintfOddNum);
	thread th2(PrintfEvenNum);

	th1.join();
	th2.join();

	std::cout << "Hello World!\n";
}

这个测试项目主要实现两个线程分别打印100以内的奇数和偶数。

代码运行后的测试结果如下:

如上图,可以实现两个线程分别打印奇数和偶数。

欢迎大家一起交流学习。

相关推荐
阿昭L3 天前
MFC仿真
c++·mfc
怎么没有名字注册了啊3 天前
MFC_Install_Create
c++·mfc
Humbunklung3 天前
unordered_map使用MFC的CString作为键值遇到C2056和C2064错误
c++·stl·mfc
夜猫逐梦3 天前
【VC】 error MSB8041: 此项目需要 MFC 库
c++·mfc
一拳一个呆瓜5 天前
【MFC】对话框属性:Absolute Align(绝对对齐)
c++·mfc
深耕AI6 天前
MFC 图形设备接口详解:小白从入门到掌握
c++·mfc
ChindongX6 天前
CMap常用函数
mfc
一拳一个呆瓜6 天前
【MFC】对话框属性:X Pos(X位置),Y Pos(Y位置)
c++·mfc
一拳一个呆瓜6 天前
【MFC】对话框属性:Center(居中)
c++·mfc
一拳一个呆瓜7 天前
【MFC】对话框:位置属性(居中、绝对对齐、X位置Y位置)应用示例
c++·mfc