C++ 经典线程同步互斥量Mutex 示例解析(十二)

2024-05-09 18:18

本文主要是介绍C++ 经典线程同步互斥量Mutex 示例解析(十二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在windows系统中,系统本身为我们提供了很多锁。通过这些锁的使用,一方面可以加强我们对锁的认识,另外一方面可以提高代码的性能和健壮性。常用的锁以下四种:

临界区:C++ 关键段(Critical Section)CS深入浅出 之多线程(七)

event :C++ 经典线程同步 事件Event(九)

信号量:信号量是使用的最多的一种锁结果,也是最方便的一种锁。围绕着信号量,人们提出了很多数据互斥访问的方案,pv操作就是其中的一种。如果说互斥锁只能对单个资源进行保护,那么信号量可以对多个资源进行保护。同时信号量在解锁的时候,可以被另外一个thread进行解锁操作。

互斥量:将是这篇文章所接触到的!

ok!本次Demo参考于MSDN:MSDN

1 首先来熟悉我们将要接触到的系列函数

CreateMutex:

HANDLE WINAPI CreateMutex(_In_opt_  LPSECURITY_ATTRIBUTES lpMutexAttributes,_In_      BOOL bInitialOwner,_In_opt_  LPCTSTR lpName
);

函数参数说明:(CreateMutex:)

第一个参数表示安全控制,一般直接传入NULL

第二个参数用来确定互斥量的初始拥有者。如果传入TRUE表示互斥量对象内部会记录创建它的线程的线程ID号并将递归计数设置为1,由于该线程ID非零,所以互斥量处于未触发状态。如果传入FALSE,那么互斥量对象内部的线程ID号将设置为NULL,递归计数设置为0,这意味互斥量不为任何线程占用,处于触发状态。

第三个参数用来设置互斥量的名称,在多个进程中的线程就是通过名称来确保它们访问的是同一个互斥量。

函数访问值:

成功返回一个表示互斥量的句柄,失败返回NULL

备注:通过CreateMutex返回的句柄有MUTEX_ALL_ACCESS访问权,它可以在需要的句柄互斥对象的任何函数中使用,前提是调用者已被授予访问权限。如果一个互斥体是由一个服务或一个线程正在模拟不同的用户创建的,你可以申请一个安全描述符来互斥,当你创建它,或者通过改变其默认的DACL更改为创建进程的默认安全描述符

OpenMutex:

HANDLE OpenMutex(
DWORDdwDesiredAccess, // access
BOOLbInheritHandle, // inheritance option
LPCTSTRlpName // object name
);

参数说明:

第一个参数表示访问权限,对互斥量一般传入MUTEX_ALL_ACCESS。详细解释可以查看MSDN文档。

第二个参数表示互斥量句柄继承性,一般传入TRUE即可。

第三个参数表示名称。某一个进程中的线程创建互斥量后,其它进程中的线程就可以通过这个函数来找到这个互斥量。

函数访问值:成功返回一个表示互斥量的句柄,失败返回NULL


ReleaseMutex:

BOOL WINAPI ReleaseMutex(_In_  HANDLE hMutex
);

参数说明:访问互斥资源前应该要调用等待函数,结束访问时就要调用ReleaseMutex()来表示自己已经结束访问,其它线程可以开始访问了。


给出CSDN的demo,demo中也有比较详细的注释!

#include <windows.h>
#include <stdio.h>#define THREADCOUNT 4 HANDLE ghWriteEvent; 
HANDLE ghThreads[THREADCOUNT];DWORD WINAPI ThreadProc(LPVOID);void CreateEventsAndThreads(void) 
{int i; DWORD dwThreadID; // Create a manual-reset event object. The write thread sets this// object to the signaled state when it finishes writing to a // shared buffer. ghWriteEvent = CreateEvent( NULL,               // default security attributesTRUE,               // manual-reset eventFALSE,              // initial state is nonsignaledTEXT("WriteEvent")  // object name); if (ghWriteEvent == NULL) { printf("CreateEvent failed (%d)\n", GetLastError());return;}// Create multiple threads to read from the buffer.for(i = 0; i < THREADCOUNT; i++) {// TODO: More complex scenarios may require use of a parameter//   to the thread procedure, such as an event per thread to  //   be used for synchronization.ghThreads[i] = CreateThread(NULL,              // default security0,                 // default stack sizeThreadProc,        // name of the thread functionNULL,              // no thread parameters0,                 // default startup flags&dwThreadID); if (ghThreads[i] == NULL) {printf("CreateThread failed (%d)\n", GetLastError());return;}}
}void WriteToBuffer(VOID) 
{// TODO: Write to the shared buffer.printf("Main thread writing to the shared buffer...\n");// Set ghWriteEvent to signaledif (! SetEvent(ghWriteEvent) ) {printf("SetEvent failed (%d)\n", GetLastError());return;}
}void CloseEvents()
{// Close all event handles (currently, only one global handle).CloseHandle(ghWriteEvent);
}int main( void )
{DWORD dwWaitResult;// TODO: Create the shared buffer// Create events and THREADCOUNT threads to read from the bufferCreateEventsAndThreads();// At this point, the reader threads have started and are most// likely waiting for the global event to be signaled. However, // it is safe to write to the buffer because the event is a // manual-reset event.WriteToBuffer();printf("Main thread waiting for threads to exit...\n");// The handle for each thread is signaled when the thread is// terminated.dwWaitResult = WaitForMultipleObjects(THREADCOUNT,   // number of handles in arrayghThreads,     // array of thread handlesTRUE,          // wait until all are signaledINFINITE);switch (dwWaitResult) {// All thread objects were signaledcase WAIT_OBJECT_0: printf("All threads ended, cleaning up for application exit...\n");break;// An error occurreddefault: printf("WaitForMultipleObjects failed (%d)\n", GetLastError());return 1;} // Close the events to clean upCloseEvents();system("pause");return 0;
}DWORD WINAPI ThreadProc(LPVOID lpParam) 
{// lpParam not used in this example.UNREFERENCED_PARAMETER(lpParam);DWORD dwWaitResult;printf("Thread %d waiting for write event...\n", GetCurrentThreadId());dwWaitResult = WaitForSingleObject( ghWriteEvent, // event handleINFINITE);    // indefinite waitswitch (dwWaitResult) {// Event object was signaledcase WAIT_OBJECT_0: //// TODO: Read from the shared buffer//printf("Thread %d reading from buffer\n", GetCurrentThreadId());break; // An error occurreddefault: printf("Wait error (%d)\n", GetLastError()); return 0; }// Now that we are done reading the buffer, we could use another// event to signal that this thread is no longer reading. This// example simply uses the thread handle for synchronization (the// handle is signaled when the thread terminates.)printf("Thread %d exiting\n", GetCurrentThreadId());return 1;
}

运行效果如下:


最后总结下互斥量Mutex

1.互斥量是内核对象,它与关键段都有“线程所有权”所以不能用于线程的同步。

2.互斥量能够用于多个进程之间线程互斥问题,并且能完美的解决某进程意外终止所造成的“遗弃”问题。


这篇关于C++ 经典线程同步互斥量Mutex 示例解析(十二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/974134

相关文章

Java中的SOLID原则及示例

类是任何Java应用程序的构建块。如果这些区块不强,那么建筑(即应用)将来将面临艰难时期。这实际上意味着,当应用程序范围上升或应用程序在生产或维护中面临某些设计问题时,不那么好的编写会导致非常困难的情况。 另一方面,一组精心设计和编写的类可以加速编码过程的突飞猛进,同时减少错误的数量。 在本教程中,我们将使用 5个最推荐的设计原则的示例来讨论Java中的SOLID原则,在编写类时我们应该记住这

Java比较和交换示例 - CAS算法

Java比较和交换示例 - CAS算法 由Lokesh Gupta | 提起下:多线程 一个Java 5中最好添加的是支持类,如原子操作AtomicInteger,AtomicLong等等。这些课程帮助您最大限度地减少复杂的(非必要)需要多线程的,如增加一些基本的操作代码或递减的值在多个线程之间共享。这些类内部依赖于名为CAS(比较和交换)的算法。在本文中,我将详细讨论这个概念。 1.乐观和

使用ThreadPoolExecutor创建线程池有哪些关键参数

1、ThreadPoolExecutor类的全参数构造方法: /*** Creates a new {@code ThreadPoolExecutor} with the given initial* parameters.** @param corePoolSize the number of threads to keep in the pool, even* if they

Linux进程与线程之五

每日一结 一 共享内存 :内核空间预留出来的一块内存,用于进程间通信  (1)int shmget(key_t key, size_t size, int shmflg); 功能:获取共享内存段的ID  参数: @key    IPC_PRIVATE  或 ftok()  @size   申请的共享内存段大小 [4k的倍

Linux进程与线程之四

每日一结 一 传统的进程间通信  1.信号 : 异步进程间通信方式    信号是对中断机制的一种模拟  进程对信号处理方式: (1)忽略信号  SIGKILL ,SIGSTOP 不能忽略  (2)捕捉 : 信号到达的时候,执行信号处理函数  (3)缺省操作 : 系统默认的操作  大部分信号默认的操作都是杀死进程,SIGCHLD 进

Linux进程与线程之三

每日一结 一 线程退出  void pthread_exit(void *retval); 功能:结束一个线程  参数: @retval  带回线程返回的地址 返回值: 无 int data = 100; pthread_exit(&data);   二 等待线程退出 int pt

Linux进程与线程之二

每日一结 一 字符串分割函数  char *strtok(char *str, const char *delim); 功能:根据分隔符号来分割字符串  参数: @str   第一次:字符串首地址    后面传递:NULL [告诉strtok函数接着上一次后面操作] @delim 分割字符串  返回值: 成功返回子串的首地址,结束返

【语音处理】wav转pcm mp3转pcm Java示例代码

【语音处理】wav转pcmJava示例代码 都是作者亲测的代码哦。因各个音频之间存在差异导致转换会存在问题。建议大家自己有习惯看源码去了解音频相关知识的能力。 代码地址:https://gitee.com/xshuai/ai/blob/master/AIDemo/src/main/java/com/xs/audio/tns/WAVConvertPCM.java Wav转PCM   p

【Python3-API】通用文字识别示例代码

Python3-urllib3-API通用OCR示例代码 AccessToken获取可以参考:http://ai.baidu.com/forum/topic/show/497663(Python3-urllib3示例)Python安装什么的。大家百度经验即可 -----------------------------------------------------下面开始代码------

【Python3-API】情感倾向分析示例代码

Python3-urllib3-API情感倾向分析示例代码 AccessToken获取可以参考:http://ai.baidu.com/forum/topic/show/497663(Python3-urllib3示例)Python安装什么的。大家百度经验即可 -----------------------------------------------------下面开始代码-----