semaphore.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/assert.h"
  5. #include "core/hle/kernel/kernel.h"
  6. #include "core/hle/kernel/semaphore.h"
  7. #include "core/hle/kernel/thread.h"
  8. namespace Kernel {
  9. Semaphore::Semaphore() {}
  10. Semaphore::~Semaphore() {}
  11. ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count,
  12. std::string name) {
  13. if (initial_count > max_count)
  14. return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::Kernel,
  15. ErrorSummary::WrongArgument, ErrorLevel::Permanent);
  16. SharedPtr<Semaphore> semaphore(new Semaphore);
  17. // When the semaphore is created, some slots are reserved for other threads,
  18. // and the rest is reserved for the caller thread
  19. semaphore->max_count = max_count;
  20. semaphore->available_count = initial_count;
  21. semaphore->name = std::move(name);
  22. return MakeResult<SharedPtr<Semaphore>>(std::move(semaphore));
  23. }
  24. bool Semaphore::ShouldWait(Thread* thread) const {
  25. return available_count <= 0;
  26. }
  27. void Semaphore::Acquire(Thread* thread) {
  28. ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
  29. --available_count;
  30. }
  31. ResultVal<s32> Semaphore::Release(s32 release_count) {
  32. if (max_count - available_count < release_count)
  33. return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel,
  34. ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  35. s32 previous_count = available_count;
  36. available_count += release_count;
  37. WakeupAllWaitingThreads();
  38. return MakeResult<s32>(previous_count);
  39. }
  40. } // namespace