c++portabilitymultiple-instancesplatform-independentmultiple-processes

Rewriting a class to be more generic for portability


I had previously asked this question Removing Windows library dependencies about removing Windows library dependencies. User: https://stackoverflow.com/users/214671/matteo-italia had already explained that for Threads you can replace windows specific code with std::mutex but as for Processes there is currently nothing in the standard which is the answer that I had accepted.

In another good answer user: https://stackoverflow.com/users/7594711/soronelhaetir had suggested using boost-interprocess. However my current project is boost free.

With this current class:

BlockProcess:

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);
}

} // namespace demo

My question is still partially the same: removing windows dependencies but now becomes: Is there a way that I can rewrite this class in a generic fashion so that I'm not inclined to have to use: #include <Windows.h> while not using any third party libraries such as boost?


Solution

  • Unfortunately the current C++ standard library does not provide much in the way of IPC and does not include any named mutex support. (It provides shared_mutex but that's a different thing.) Therefore you're stuck with external dependencies. That external dependency can be the Windows API as you've done, or Boost (which provides a named_mutex), or something else.

    I completely understand your reluctance to introduce a dependency on Boost. But if you try to handle this yourself and start to add alternative platform support, you'll quickly find that you're simply reinventing the Boost libraries and almost certainly not doing as good a job. So in this case you should weigh your requirements for portability against your distaste for biting the bullet and using Boost.