2014-12-03 23:49:51 +00:00
|
|
|
// Copyright 2014 Citra Emulator Project
|
2014-12-17 05:38:14 +00:00
|
|
|
// Licensed under GPLv2 or any later version
|
2014-12-03 23:49:51 +00:00
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
2015-05-06 07:06:12 +00:00
|
|
|
#include "common/assert.h"
|
2017-05-21 07:11:36 +00:00
|
|
|
#include "core/hle/kernel/errors.h"
|
2014-12-03 23:49:51 +00:00
|
|
|
#include "core/hle/kernel/kernel.h"
|
2016-09-21 06:52:38 +00:00
|
|
|
#include "core/hle/kernel/semaphore.h"
|
2014-12-03 23:49:51 +00:00
|
|
|
#include "core/hle/kernel/thread.h"
|
|
|
|
|
|
|
|
namespace Kernel {
|
|
|
|
|
2016-09-19 01:01:46 +00:00
|
|
|
Semaphore::Semaphore() {}
|
|
|
|
Semaphore::~Semaphore() {}
|
2015-02-01 00:56:59 +00:00
|
|
|
|
2015-01-11 15:53:11 +00:00
|
|
|
ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count,
|
2016-09-18 00:38:01 +00:00
|
|
|
std::string name) {
|
2014-12-04 16:40:36 +00:00
|
|
|
|
2014-12-13 01:46:52 +00:00
|
|
|
if (initial_count > max_count)
|
2017-05-21 07:11:36 +00:00
|
|
|
return ERR_INVALID_COMBINATION_KERNEL;
|
2014-12-13 01:46:52 +00:00
|
|
|
|
2015-01-11 15:53:11 +00:00
|
|
|
SharedPtr<Semaphore> semaphore(new Semaphore);
|
2014-12-03 23:49:51 +00:00
|
|
|
|
2014-12-04 16:55:13 +00:00
|
|
|
// When the semaphore is created, some slots are reserved for other threads,
|
|
|
|
// and the rest is reserved for the caller thread
|
2014-12-13 01:46:52 +00:00
|
|
|
semaphore->max_count = max_count;
|
2014-12-13 03:22:11 +00:00
|
|
|
semaphore->available_count = initial_count;
|
2015-01-11 15:53:11 +00:00
|
|
|
semaphore->name = std::move(name);
|
2014-12-03 23:49:51 +00:00
|
|
|
|
2015-01-11 15:53:11 +00:00
|
|
|
return MakeResult<SharedPtr<Semaphore>>(std::move(semaphore));
|
2014-12-04 16:40:36 +00:00
|
|
|
}
|
|
|
|
|
2017-01-01 21:53:22 +00:00
|
|
|
bool Semaphore::ShouldWait(Thread* thread) const {
|
2015-01-11 15:53:11 +00:00
|
|
|
return available_count <= 0;
|
|
|
|
}
|
|
|
|
|
2017-01-01 21:53:22 +00:00
|
|
|
void Semaphore::Acquire(Thread* thread) {
|
2017-01-02 00:07:37 +00:00
|
|
|
if (available_count <= 0)
|
|
|
|
return;
|
2015-01-11 15:53:11 +00:00
|
|
|
--available_count;
|
|
|
|
}
|
2014-12-04 16:40:36 +00:00
|
|
|
|
2015-01-11 15:53:11 +00:00
|
|
|
ResultVal<s32> Semaphore::Release(s32 release_count) {
|
|
|
|
if (max_count - available_count < release_count)
|
2017-05-21 07:11:36 +00:00
|
|
|
return ERR_OUT_OF_RANGE_KERNEL;
|
2014-12-04 16:40:36 +00:00
|
|
|
|
2015-01-11 15:53:11 +00:00
|
|
|
s32 previous_count = available_count;
|
|
|
|
available_count += release_count;
|
2014-12-04 16:40:36 +00:00
|
|
|
|
2015-06-08 03:39:37 +00:00
|
|
|
WakeupAllWaitingThreads();
|
2015-05-20 00:24:30 +00:00
|
|
|
|
2015-01-11 15:53:11 +00:00
|
|
|
return MakeResult<s32>(previous_count);
|
2014-12-03 23:49:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace
|