Skip to content

Commit

Permalink
Use std::atomic
Browse files Browse the repository at this point in the history
  • Loading branch information
gammasoft71 committed Sep 15, 2023
1 parent d3d001b commit f918f67
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/xtd.core/src/xtd/threading/unnamed_semaphore.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "../../../include/xtd/semaphore.h"
#include "../../../include/xtd/invalid_operation_exception.h"
#include "../../../include/xtd/threading/interlocked.h"
#include <atomic>

class xtd::threading::semaphore::unnamed_semaphore : public semaphore_base {
public:
Expand All @@ -22,7 +23,7 @@ class xtd::threading::semaphore::unnamed_semaphore : public semaphore_base {
handle_ = std::make_shared<data>();
handle_->maximum_count = maximum_count;
handle_->semaphore.release(static_cast<std::ptrdiff_t>(initial_count));
interlocked::exchange(handle_->count, handle_->count + initial_count);
handle_->count += initial_count;
return true;
}

Expand All @@ -43,22 +44,22 @@ class xtd::threading::semaphore::unnamed_semaphore : public semaphore_base {
if (handle_->count + release_count > handle_->maximum_count) return false;
previous_count = handle_->count;
handle_->semaphore.release(static_cast<std::ptrdiff_t>(release_count));
interlocked::exchange(handle_->count, handle_->count + release_count);
handle_->count += release_count;
return true;
}

uint32 wait(int32 milliseconds_timeout) override {
if (milliseconds_timeout == timeout::infinite) handle_->semaphore.acquire();
else if (handle_->semaphore.try_acquire_for(std::chrono::milliseconds {milliseconds_timeout}) == false) return 0x00000102;

interlocked::decrement(handle_->count);
--handle_->count;
return 0x00000000;
}

private:
struct data {
int count = 0;
int maximum_count = std::numeric_limits<int>::max();
std::atomic<int32> count = 0;
std::atomic<int32> maximum_count = std::numeric_limits<int>::max();
std::counting_semaphore<int32_object::max_value> semaphore {0};
};
std::shared_ptr<data> handle_;
Expand Down

0 comments on commit f918f67

Please sign in to comment.