我是靠谱客的博主 缓慢飞机,这篇文章主要介绍c++利用mutex(互斥量)实现多线程,现在分享给大家,希望可以做个参考。

C++使用内核对象互斥体(Mutex)实现线程同步锁,当两个线程共同访问一个共享资源时,Mutex可以只向一个线程授予访问权。

下面的例子模拟了售票系统,定义了两个售票线程

/// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
//mutex
#include "stdafx.h"
#include <stdio.h>
#include<windows.h>
#include<process.h>
void __cdecl  threadProc1(void* param);
void __cdecl  threadProc2(void* param);
int tickets = 100;
HANDLE hMutex = INVALID_HANDLE_VALUE;
int main()
{
    hMutex = CreateMutex(NULL, FALSE, NULL);
    HANDLE hThread1 =(HANDLE)_beginthread(threadProc1, 0, "A:");
    HANDLE hThread2 = (HANDLE)_beginthread(threadProc2, 0, "B:");
    HANDLE hThread[] = { hThread1 ,hThread2 };
    WaitForMultipleObjects(2, hThread, true, INFINITE);
    return 0;
}
void __cdecl  threadProc1(void* param) {
    char *p = (char *)param;
    while (tickets > 0) {
        WaitForSingleObject(hMutex, INFINITE);//等待Mutex释放
        if (tickets > 0) {
            printf("%s sell ticket %dn", p, tickets--);
        }
        ReleaseMutex(hMutex);//释放mutex
    }
}
void __cdecl  threadProc2(void* param) {
    char *p = (char *)param;
    while (tickets > 0) {
        WaitForSingleObject(hMutex, INFINITE);//等待Mutex释放
        if (tickets > 0) {
            printf("%s sell ticket %dn", p, tickets--);
        }
        ReleaseMutex(hMutex);//释放mutex
    }
}

最后

以上就是缓慢飞机最近收集整理的关于c++利用mutex(互斥量)实现多线程的全部内容,更多相关c++利用mutex(互斥量)实现多线程内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部