|
Revision 36273, 1.5 kB
(checked in by saturday06, 3 years ago)
|
|
おいおいお
|
| Line | |
|---|
| 1 | #pragma once
|
|---|
| 2 | #include "Mil.h"
|
|---|
| 3 | #include "Synchronize.h"
|
|---|
| 4 |
|
|---|
| 5 | /**
|
|---|
| 6 | * XXX CAST!!!
|
|---|
| 7 | */
|
|---|
| 8 | namespace mil {
|
|---|
| 9 | class Serial {
|
|---|
| 10 | public:
|
|---|
| 11 | enum {
|
|---|
| 12 | INVALID_VALUE = -1,
|
|---|
| 13 | };
|
|---|
| 14 | private:
|
|---|
| 15 | Mutex mutex;
|
|---|
| 16 | int max;
|
|---|
| 17 | int serial;
|
|---|
| 18 | void* list_; // avoid compiler's segv
|
|---|
| 19 | public:
|
|---|
| 20 | Serial(int max) : max(max), serial(0) {
|
|---|
| 21 | list_ = reinterpret_cast<void*>(new std::list<int>());
|
|---|
| 22 | }
|
|---|
| 23 |
|
|---|
| 24 | ~Serial() {
|
|---|
| 25 | delete reinterpret_cast<std::list<int>*>(list_);
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | int retain() {
|
|---|
| 29 | int new_id = INVALID_VALUE;
|
|---|
| 30 | synchronized (mutex) {
|
|---|
| 31 | std::list<int>& list = *reinterpret_cast<std::list<int>*>(list_);
|
|---|
| 32 | try {
|
|---|
| 33 | if (!list.empty()) {
|
|---|
| 34 | int v = list.back();
|
|---|
| 35 | list.pop_back();
|
|---|
| 36 | return v;
|
|---|
| 37 | }
|
|---|
| 38 | } catch (std::exception&) {
|
|---|
| 39 | halt << "insufficient memory";
|
|---|
| 40 | return INVALID_VALUE;
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | if (serial >= max) {
|
|---|
| 44 | return INVALID_VALUE;
|
|---|
| 45 | }
|
|---|
| 46 | new_id = serial;
|
|---|
| 47 | serial++;
|
|---|
| 48 | }
|
|---|
| 49 | return new_id;
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | bool release(int v) {
|
|---|
| 53 | synchronized (mutex) {
|
|---|
| 54 | std::list<int>& list = *reinterpret_cast<std::list<int>*>(list_);
|
|---|
| 55 | try {
|
|---|
| 56 | list.push_back(v);
|
|---|
| 57 | } catch (std::exception&) {
|
|---|
| 58 | return false;
|
|---|
| 59 | }
|
|---|
| 60 | }
|
|---|
| 61 | return true;
|
|---|
| 62 | }
|
|---|
| 63 | };
|
|---|
| 64 | }
|
|---|