123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- /**
- *
- * @file singleton.hpp
- * @author zxw
- * Copyright 2024, yjrobotics. All rights reserved.
- *
- * robotics
- *
- */
- #pragma once
- //stl
- #include <iostream>
- #ifdef WINDOWS_BUILD
- #include <windows.h>
- #elif LINUX_BUILD
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdio.h>
- #endif
- namespace robotics {
- namespace v3 {
- class singleton {
- public:
- explicit singleton() {
- }
- bool locker(std::string const& value) {
- #ifdef WINDOWS_BUILD
- mutex_ = CreateMutex(NULL, TRUE, value.c_str());
- return GetLastError() == ERROR_ALREADY_EXISTS;
- #elif LINUX_BUILD
- std::string file = "/tmp/" + value + ".lock";
- fd_ = open(file.c_str(), O_CREAT | O_RDWR, 0666);
- return flock(fd, LOCK_EX | LOCK_NB) == -1;
- #endif
- }
- ~singleton() {
- #ifdef WINDOWS_BUILD
- ReleaseMutex(mutex_);
- CloseHandle(mutex_);
- #elif LINUX_BUILD
- flock(fd_, LOCK_UN);
- close(fd_);
- #endif
- }
- private:
- #ifdef WINDOWS_BUILD
- HANDLE mutex_ = nullptr;
- #elif LINUX_BUILD
- int fd_ = 0;
- #endif
- };
- }
- }
|