我这里有几个类,出于可移植性的原因,我想删除这些类与窗口库的依赖关系。一个用于阻塞进程,另一个用于阻塞线程。这两个类都编译;运行正常。。。至于
BlockProcess
类当前正在使用
HANDLE
对于互斥体并使用函数调用,例如:{
CreateMutex()
,
CloseHandle()
&
GetLastError()
}. 至于
BlockThread
类,它使用指向
CRITICAL_SECTION
调用函数,例如:{
EnterCricticalSection()
&
LeaveCriticalSection()
}.
我想知道的是,有没有一种等效的方法可以使用
std
库,例如
std::mutex
,
std::thread
等,以提供相同的功能。我想消除
#include<windows.h>
&可能地
#include<process.h>
.
以下是我现有的课程:
BlockProcess.h
#ifndef BLOCK_PROCESS_H
#define BLOCK_PROCESS_H
#include <Windows.h>
#include <process.h>
#include <string>
namespace demo {
class BlockProcess final {
private:
HANDLE hMutex_;
public:
explicit BlockProcess( const std::string& strName );
~BlockProcess();
bool isBlocked() const;
BlockProcess( const BlockProcess& c ) = delete;
BlockProcess& operator=( const BlockProcess& c ) = delete;
};
} // namespace demo
#endif // !BLOCK_PROCESS_H
BlockProcess.cpp
#include "BlockProcess.h"
namespace demo {
BlockProcess::BlockProcess( const std::string& strName ) {
hMutex_ = CreateMutex( nullptr, FALSE, strName.c_str() );
}
BlockProcess::~BlockProcess() {
CloseHandle( hMutex_ );
}
bool BlockProcess::isBlocked() const {
return (hMutex_ == nullptr || GetLastError() == ERROR_ALREADY_EXISTS);
}
BlockThread.h
#ifndef BLOCK_THREAD_H
#define BLOCK_THREAD_H
#include <Windows.h>
namespace demo {
class BlockThread final {
private:
CRITICAL_SECTION* pCriticalSection_;
public:
explicit BlockThread( CRITICAL_SECTION& criticalSection );
~BlockThread();
BlockThread( const BlockThread& c ) = delete;
BlockThread& operator=( const BlockThread& c ) = delete;
};
} // namespace demo
#endif // !BLOCK_THREAD_H
} // namespace demo
BlockThread.cpp
#include "BlockThread.h"
namespace demo {
BlockThread::BlockThread( CRITICAL_SECTION& criticalSection ) {
pCriticalSection_ = &criticalSection;
EnterCriticalSection( pCriticalSection_ );
}
BlockThread::~BlockThread() {
LeaveCriticalSection( pCriticalSection_ );
}
} // namespace demo
编辑
如果您需要一个如何使用这些类的示例,请随时留下评论。