CCriticalSection与CSingleLock

CCriticalSection与CSingleLockCCriticalSectionAnobjectofclassCCriticalSectionrepresentsa“criticalsection”—asynchronizationobjectthatallowsonethreadatatimetoaccessaresourceorsectionofcode.Criticalse

大家好,又见面了,我是你们的朋友全栈君。

CCriticalSection

CCriticalSection与CSingleLock

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

CCriticalSection Constructs a CCriticalSection object.

Methods

Unlock Releases 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.

Lock Use 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;
		}
		else
			break;
		//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;
		}
		else
			break;
		//g_CriticalSection.Unlock();
		sLock.Unlock();
	}
	cout<<"thread2 is running!"<<endl;
	return 0;
}

CCriticalSection与CSingleLock

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/162022.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • oracle数据库菜鸟入门

    oracle数据库菜鸟入门所有应用软件之中,数据库可能是最复杂的。MySQL的手册有3000多页,PostgreSQL的手册有2000多页,Oracle的手册更是比它们相加还要厚。但是,自己写一个最简单的数据库,做起来并不难。Reddit上面有一个帖子,只用了几百个字,就把原理讲清楚了。下面是我根据这个帖子整理的内容。一、数据以文本形式保存第一步,就是将所要保存的数据,写入文本文件。这个文本文件就是你的数据库。为了方便读取,数据必须分成记录,每一条记录的长度规定为等长。比如,假定每条记录的长度是800字节,那

    2022年8月30日
    3
  • KAZE特征的理解

    KAZE特征的理解毕设要做图像配准,计划使用KAZE特征进行特征点的检测,以下是我对KAZE算法原理的理解,有什么不对的地方,希望提出来大家相互讨论学习。一、KAZE算法的由来KAZE算法是由法国学者在在2012年的ECCV会议中提出的,是一种比SIFT更稳定的特征检测算法。KAZE的取名是为了纪念尺度空间分析的开创者—日本学者Iijima。KAZE在日语中是‘风’的谐音,寓意是就像风的形成是空气在空间中非线性…

    2022年6月29日
    33
  • ubuntu 下 vlc ,smplayer 播放电影时字幕乱码解决方法

    ubuntu 下 vlc ,smplayer 播放电影时字幕乱码解决方法自:http://blog.sina.com.cn/s/blog_70545bad01015ky1.htmlubuntu下vlc,smplayer播放电影时出现乱码,令人头疼的很,不知道该怎么办,网上查了一些方法,但是没有一个能成功的,也许是我的方法不正确,没办法,只能将就看一下英文字幕,或者有时候看不懂的时候干脆切换到win7底下看,但这终究不是解决的方法,从网上查了很多方法,但是

    2022年7月11日
    28
  • DICOM影像中的窗宽窗位

    DICOM影像中的窗宽窗位1.为什么有窗宽窗位?医学图像领域的关键技术窗技术,是CT检查中用以观察不同密度的正常组织或病变的一种显示技术,包括窗宽(windowwidth)和窗位(windowlevel)。由于各种组织结构或病变具有不同的CT值,因此想要显示某一组织结构细节时,应该选择适合观察该组织或病变的窗宽和窗位,以获得最佳显示。2.窗宽窗宽是CT图像上显示的CT值范围,在此CT值范围内的组织和病变均

    2022年6月29日
    55
  • 使用 Java DB (Derby) 数据库

    使用 Java DB (Derby) 数据库使用JavaDB(Derby)数据库https://netbeans.org/kb/docs/ide/java-db_zh_CN.html本文档说明了如何在NetBeansIDE中设置与JavaDB数据库的连接。在建立连接之后,即可开始在IDE中使用该数据库,您可以执行的操作包括创建表、用数据填充表、运行SQL语句和查询等。…

    2022年7月8日
    23
  • 华为交换机配置不同vlan不同网段互通[通俗易懂]

    华为交换机配置不同vlan不同网段互通[通俗易懂]在一台交换机中实现不同vlan不同网段相互通信Pc1:Pc2:Sw1:<Huawei>system-view1、创建vlan[Huawei]vlan2[Huawei-vlan2]quit[Huawei]vlan3[Huawei-vlan3]quit2、进入接口配置[Huawei]interfaceGigabitEthernet0/0/1[Huaw…

    2025年9月7日
    13

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号