I want to allocate an array of interprocess_semaphore object
initialized with 0 counter value. This class is a part of boost
library used for thread synchronization.
class interprocess_semaphore {
public:
// construct/copy/destruct
interprocess_semaphore(int);
~interprocess_semaphore();
// public member functions
void post() ;
void wait() ;
bool try_wait() ;
bool timed_wait(const boost::posix_time::ptime &) ;
};
---
interprocess_semaphore* ready_sem;
ready_sem = new interprocess_semaphore[maxFloor;
Since the class has no default constructor, the compiler gives error.
When I try to use vector, I solve the initialization problem. But at
this time, there is another roblem related with copying semaphores.
vector<interprocess_semaphore> ready_sem;
ready_sem.reserve(maxFloor);
for (int i = 0;i < maxFloor; ++i)
ready_sem.push_back(* new boost::interprocess::interprocess_semaphore
(0));
All I want to do is allocating an array of semephore objects with 0
initial counter value. How can I do that in C++ ?
yatko
Assuming the objects are copyable (copy constructor and assignment
operator),
vector<interprocess_semaphore> ready_sem( maxFloor, 0 );
Cheers & hth.,
- Alf
Hi Yatko
I have the following suggestions for you:
1. If semaphore objects usually have initial value (0), it is better
to declare your class
like this:
class interprocess_semaphore {
public:
interprocess_semaphore(int = 0); // default ctor
// as before
};
2. Of course it is not a good idea, but if you like to use array over
vector, you can use the following code:
interprocess_semaphore** ready_sem = new interprocess_semaphore*
[maxFloor];
for (int i = 0; i < maxFloor; i++) {
interprocess_semaphore* p = new interprocess_semaphore(0);
ready_sem[i] = p;
}
// use array ...
for (int i = 0; i < maxFloor; i++) {
delete ready_sem[i];
}
delete [] ready_sem;
Regards,
- Saeed
Thanks for your postings and I am very sorry that less information.
> Hi Yatko
> I have the following suggestions for you:
> 1. If semaphoreobjectsusually have initial value (0), it is better
> to declare your class
> like this:
> class interprocess_semaphore {
> public:
> interprocess_semaphore(int = 0); // default ctor
> // as before
> };
First, the interprocess_class is a part of boost library and it is
designed with one-parameter constructor. I could not have the chance
of redeclare the overall class.
> 2. Of course it is not a good idea, but if you like to usearrayover
> vector, you can use the following code:
> interprocess_semaphore** ready_sem = new interprocess_semaphore*
> [maxFloor];
>
> for (int i = 0; i < maxFloor; i++) {
> interprocess_semaphore* p = new interprocess_semaphore(0);
> ready_sem[i] = p;
> }
>
> // usearray...
>
> for (int i = 0; i < maxFloor; i++) {
> delete ready_sem[i];
> }
>
> delete [] ready_sem;
>
> Regards,
> - Saeed
Second, I have tried to use vector, but since the class is designed as
noncopyable, the compiler gives errors. Finally, I have decided to use
array of pointers and it works fine.
Thanks