singleton.hpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. *
  3. * @file singleton.hpp
  4. * @author zxw
  5. * Copyright 2024, yjrobotics. All rights reserved.
  6. *
  7. * robotics
  8. *
  9. */
  10. #pragma once
  11. //stl
  12. #include <iostream>
  13. #ifdef WINDOWS_BUILD
  14. #include <windows.h>
  15. #elif LINUX_BUILD
  16. #include <fcntl.h>
  17. #include <unistd.h>
  18. #include <stdio.h>
  19. #endif
  20. namespace robotics {
  21. namespace v3 {
  22. class singleton {
  23. public:
  24. explicit singleton() {
  25. }
  26. bool locker(std::string const& value) {
  27. #ifdef WINDOWS_BUILD
  28. mutex_ = CreateMutex(NULL, TRUE, value.c_str());
  29. return GetLastError() == ERROR_ALREADY_EXISTS;
  30. #elif LINUX_BUILD
  31. std::string file = "/tmp/" + value + ".lock";
  32. fd_ = open(file.c_str(), O_CREAT | O_RDWR, 0666);
  33. return flock(fd, LOCK_EX | LOCK_NB) == -1;
  34. #endif
  35. }
  36. ~singleton() {
  37. #ifdef WINDOWS_BUILD
  38. ReleaseMutex(mutex_);
  39. CloseHandle(mutex_);
  40. #elif LINUX_BUILD
  41. flock(fd_, LOCK_UN);
  42. close(fd_);
  43. #endif
  44. }
  45. private:
  46. #ifdef WINDOWS_BUILD
  47. HANDLE mutex_ = nullptr;
  48. #elif LINUX_BUILD
  49. int fd_ = 0;
  50. #endif
  51. };
  52. }
  53. }