CCriticalSection与CSingleLock

article/2025/10/29 6:02:24

CCriticalSection

An object of class CCriticalSection represents a “critical section” — a synchronization object that allows one thread at a time to access a resource or section of code. Critical sections are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CCriticalSection object to control the linked list, only one thread at a time can gain access to the list.

Critical sections are used instead of mutexes when speed is critical and the resource will not be used across process boundaries. For more information on using mutexes in MFC, see CMutex.

To use a CCriticalSection object, construct the CCriticalSection object when it is needed. You can then access the critical section when the constructor returns. Call Unlock when you are done accessing the critical section.

To access a resource controlled by a CCriticalSection object in this manner, first create a variable of type CSingleLock in your resource’s access member function. Then call the lock object’s Lock member function (for example, CSingleLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, use the lock object’s Unlock member function (for example, CSingleLock::Unlock), or allow the lock object to fall out of scope.

Alternatively, you can create a CCriticalSection object stand-alone, and access it explicitly before attempting to access the controlled resource. This method, while clearer to someone reading your source code, is more prone to error as you must remember to lock and unlock the critical section before and after access.

For more information on using CCriticalSection objects, see the articleMultithreading: How to Use the Synchronization Classes in Visual C++ Programmer's Guide.

#include <afxmt.h>


        临界段CCriticalSection可以单独使用,也可以和CSingleLock使用,从性能上讲,临界段要优于互斥量,它是一个用于同步的对象,同一时刻只允许一个线程存取资源或代码区。临界段在控制一次只允许一个线程修改数据或其它的控制资源时非常有用,例如在链表中增加一个结点就只允许一次一个线程进行。通过使用临界段来控制链表,就可以达到这个目的。它就像是一把钥匙,哪个线程获得了它就获得了运行线程的权力,而把其他线程统统阻塞。使用是临界段要先定义在一个全局变量,比如在一个类中声明为数据成员、静态变量、或全局变量。临界段使用一个就够了,用时lock,要保护的资源放这里,不用时unlock,资源不再受保护。CCriticalSection是对CRITICAL_SECTION的封装。

        临界段

CCriticalSection Class Members

Construction

CCriticalSectionConstructs a CCriticalSection object.

Methods

UnlockReleases the CCriticalSection object.

virtual BOOL Unlock( );

Return Value

Nonzero if the CCriticalSection object was owned by the thread and the release was successful; otherwise 0.

Remarks

Releases the CCriticalSection object for use by another thread. If the CCriticalSection is being used stand-alone, Unlock must be called immediately after completing use of the resource controlled by the critical section. If a CSingleLock object is being used, CCriticalSection::Unlock will be called by the lock object’s Unlock member function.

LockUse to gain access to the CCriticalSection object.

BOOL Lock( );  //不带超时参数

BOOL Lock( DWORD dwTimeout ); //带超时参数

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

dwTimeout

Lock ignores this parameter value.

Remarks

Call this member function to gain access to the critical section object. Lock is a blocking call that will not return until the critical section object is signaled (becomes available).

If timed waits are necessary, you can use a CMutex object instead of a CCriticalSection object.

CSingleLock

CSingleLock does not have a base class.

An object of class CSingleLock represents the access-control mechanism used in controlling access to a resource in a multithreaded program. In order to use the synchronization classes CSemaphore, CMutex, CCriticalSection, and CEvent, you must create either a CSingleLock or CMultiLock object to wait on and release the synchronization object. Use CSingleLock when you only need to wait on one object at a time. Use CMultiLock when there are multiple objects that you could use at a particular time.

To use a CSingleLock object, call its constructor inside a member function in the controlled resource’s class. Then call the IsLocked member function to determine if the resource is available. If it is, continue with the remainder of the member function. If the resource is unavailable, either wait for a specified amount of time for the resource to be released, or return failure. After use of the resource is complete, either call the Unlock function if the CSingleLock object is to be used again, or allow the CSingleLock object to be destroyed.

CSingleLock objects require the presence of an object derived from CSyncObject. This is usually a data member of the controlled resource’s class. For more information on how to use CSingleLock objects, see the articleMultithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

#include <afxmt.h>


一个CSingleLock类对象代表一种访问控制机制,这种机制用于控制在一个多线程程序中对一个资源的访问。为了使用同步类CSemaphore,CMutex,CCriticalSection和CEvent,必须创建一个CSingleLock或CMultiLock对象来等待和释放这个同步对象。当每次等待一个对象时,可以使用CSingleLock,当在一个特别的时候你可以使用多个对象时,可以使用CMultiLock。


#include <iostream.h>
#include <afxmt.h>
#include <Afxwin.h>UINT Fun1Proc(LPVOID lpParameter   // thread data
);UINT Fun2Proc(LPVOID lpParameter   // thread data
);int tickets=100;
CCriticalSection g_CriticalSection;void main()
{AfxBeginThread(Fun1Proc,NULL);AfxBeginThread(Fun2Proc,NULL);Sleep(4000);
}UINT Fun1Proc(LPVOID lpParameter   // thread data
)
{while(TRUE){//g_CriticalSection.Lock();CSingleLock sLock(&g_CriticalSection);sLock.Lock();if(tickets>0){Sleep(1);cout<<"thread1 sell ticket : "<<tickets--<<endl;}elsebreak;//g_CriticalSection.Unlock();sLock.Unlock();}cout<<"thread1 is running!"<<endl;return 0;
}UINT Fun2Proc(LPVOID lpParameter   // thread data
)
{while(TRUE){//g_CriticalSection.Lock();CSingleLock sLock(&g_CriticalSection);sLock.Lock();if(tickets>0){Sleep(1);cout<<"thread2 sell ticket : "<<tickets--<<endl;}elsebreak;//g_CriticalSection.Unlock();sLock.Unlock();}cout<<"thread2 is running!"<<endl;return 0;
}



http://chatgpt.dhexx.cn/article/0Pg0GHNi.shtml

相关文章

关键部分CCriticalSection使用

类CCriticalSection的对象表示一个“临界区”&#xff0c;它是一个用于同步的对象&#xff0c;同一时刻仅仅同意一个线程存取资源或代码区。临界区在控制一次仅仅有一个线程改动数据或其他的控制资源时很实用。比如&#xff0c;在链表中添加一个结点就仅仅同意一次一个线程进行…

模拟售票大厅实例——多线程时访问共享变量时的安全(CMutex或CCriticalSection的应用)

当程序运行时&#xff0c;可以通过多线程来提高程序运行的效率和拥有更好的体验。但多线程&#xff08;或多进程&#xff09;同时也带来很多的问题&#xff1a;最严重的莫过于对同一个对象或变量访问时&#xff0c;由于线程运行异步的原因&#xff0c;会造成程序运行出现无法控…

在MFC下面实际演示CCriticalSection 的使用

Q&#xff1a;CCriticalSection是什么&#xff1f; A&#xff1a;CCriticalSection是一种线程同步策略 或者说技术 或者方法 总之呢就是这么个意思。。。。 参考资料&#xff1a; http://blog.csdn.net/akof1314/article/details/5773076 http://www.cnblogs.com/hlxs/archi…

Android对话框总结(普通对话框,单选对话框,多选对话框,自定义对话框)

个人推荐: &#x1f4e2;&#x1f4e2;&#x1f4e2; 前些天发现了一个蛮有意思的人工智能学习网站,8个字形容一下 "通俗易懂&#xff0c;风趣幽默"&#xff0c;感觉非常有意思,忍不住分享一下给大家。点击跳转到教程。 一:AlterDialog对话框 二:普通对话框 运行效果…

Android对话框显示输入框

在弹出的对话框显示输入框有两种方法&#xff1a; 法一&#xff1a;新建一个布局&#xff0c;并在对话框中引用它。 法二&#xff1a;直接在Activity中定义Edit并在对话框中用getText方法得到输入信息。

Android对话框的使用

Android对话框的使用 对话框&#xff08;Dialog&#xff09;是Android系统在Activity或者其他组件运行过程中提供的一种提示机制。它可以帮助应用完成一些必要的提示功能&#xff0c;同时提供一些与用户交互的功能。 对话框分为很多种&#xff0c;下面将一一介绍…

android 自定义对话框

// 基础库 implementation com.github.goweii.AnyLayer:anylayer:2.5.0 // 通用弹窗&#xff08;依赖基础库&#xff09; implementation com.github.goweii.AnyLayer:anylayer-common:2.5.0 编写dialog_layout 布局 <?xml version"1.0" encoding"utf-8&qu…

Android对话框的使用总结

一&#xff0e;相关概念 一个对话框一般是一个出现在当前Activity之上的一个小窗口. 处于下面的Activity失去焦点, 对话框接受所有的用户交互. 对话框一般用于提示信息和与当前应用程序直接相关的小功能. Android API 支持下列类型的对话框对象: &#xff08;一&#x…

Android对话框控件读写,Android 对话框控件

对话框控件 一、概述 对话框是 UI 设计中常用的控件&#xff0c;在windows操作系统中&#xff0c;对话框可分为模式对话框和非模式对话框。 模式对话框在使用时&#xff0c;项目中其它UI是不允许操作的&#xff0c;如保存对文件话框 非模式对话框允许操作其它的 UI Android 的对…

Android对话框总结

一、什么是对话框&#xff1f; 一种次要窗口&#xff0c;包含按钮和各种选项&#xff0c;通过它们可以完成特定命令或任务。 查找和替换对话框 对话框与窗口有区别&#xff0c;它没有最大化按钮、没有最小化按钮、大都不能改变形状大小。&#xff08;“打开文件”对话框是可以改…

Android常用对话框

学习目标&#xff1a; 两周入门Android 学习内容&#xff1a; 常见对话框: 对话框是程序与用户交互的一种方式&#xff0c;通常用于显示当前程序提示信息以及相关说明,以小窗口形式展现 普通对话框&#xff1a; 通过AlertDialog.Builder(this).create来创建对话框最后通过…

了解Android布局,了解Android对话框布局

我正在为我的android应用程序做一个简单的自定义对话框&#xff0c;只显示一个搜索栏。然而&#xff0c;这个简单任务的复杂性让我很烦。了解Android对话框布局 我的对话框布局如下&#xff1a;在代码中创建 android:orientation"vertical" android:layout_width&quo…

Android对话框(普通对话框、单选对话框、多选对话框、进度条对话框)

一、普通对话框 // 通过builder 构建器来构造AlertDialog.Builder builder = new Builder(this);builder.setTitle("警告");builder.setMessage("你好么 ");builder.setPositiveButton("好", new OnClickListener() {@Overridepublic void onCl…

android 对话框窗口,Android 对话框详解(一)

对话框是程序运行中的弹出窗口。例如&#xff0c;当用户要删除一个联系方式时&#xff0c;会弹出一个 对话框&#xff0c;让用户确认是否真的要删除。 Android系统提供了四种对话框:警告对话框 (AlertDialog)、进度对话框(ProgressDialog)、日期选择对话框(DatePickerDialog)和…

Android对话框

(不足之处,多多担待) 一: 对话框的种类 1:提示对话框 2:自定义对话框 3:弹出对话框 二:设置对话框的详细步骤 1:提示对话框 在activity中设置代码实现功能 , 第一步实例化对话框 第二步是设置对话框的提示内容 ,有4个主要方法 (窗贴提示内容:setTitle() / setMessage()…

Android常用对话框大全——Dialog

唉&#xff01;最近一直忙碌着写项目以至于都没有空出点时间来总结近期的学习&#xff0c; 记录学习到的东西…现在正好有时间了就该好好记录一下学习的过程了。 今天就来谈谈开发中经常用的到的一个控件——Dialog&#xff0c;对话框一般我们就用来提示一些信息给用户&#…

Android 对话框(Dialog)

对话框是提示用户做出决定或输入额外事件的小窗口。对话框不会填充屏幕&#xff0c;通常用于需要用户采取行动才能继续执行的模式事件。 Dialog类是对话框的基类&#xff0c;我们可以使用Dialog来构建一个对话框。但Android建议避免直接使用Dialog&#xff0c;而应该使用其子类…

android十大常用对话框

Android十大常用对话框 一、对话框效果二、代码 最近老师叫我们整理android常用的对话框&#xff0c;我整理了十种对话框&#xff0c;用于分享交流&#xff0c;希望指正&#xff01; 一、对话框效果 主界面 1.普通对话框 2.单选对话框 3.多选对话框 4.列表对话框 5.不带进…

Android常用的几种对话框

1文本提示对话框 AlertDialog.Builder b new AlertDialog.Builder(this);//this为上下文&#xff0c;如果在本类里显示&#xff0c;通常使用this b.setTitle("标题");/对话框标题 b.setMessage("可能会删除某个文件");//提示文本 …

Android对话框的详细介绍(提示对话框,自定义对话框)

简介&#xff1a; 我们都知道在Android开发中&#xff0c;当我们的程序在与用户交互时&#xff0c;用户会得到一定的反馈&#xff0c;其中以对话框的形式的反馈还是比较常见的&#xff0c;接下来我们来介绍几种常见的对话框的基本使用。 前置准备&#xff1a;&#xff08;文章…