instance counter

M

Moshbear dot Net

Given
class Fred {
public:
Fred() {
ctr = ++xctr;
}
....
private:
unsigned ctr;
static unsigned xctr; // initialized via boost::thread::run_once
....
};
,
what would be the best way to make the increment-and-read of xctr
atomic so that it is thread-safe?
I'm using xctr to track instance number of class so that I can use
operator<(const Fred&) to compare by instance-creation time.
 
C

Chris M. Thomasson

Moshbear dot Net said:
Given
class Fred {
public:
Fred() {
ctr = ++xctr;
}
...
private:
unsigned ctr;
static unsigned xctr; // initialized via boost::thread::run_once
...
};
,
what would be the best way to make the increment-and-read of xctr
atomic so that it is thread-safe?

Perhaps an atomic fetch-and-add operation, or a statically initialized
PThread mutex.

I'm using xctr to track instance number of class so that I can use
operator<(const Fred&) to compare by instance-creation time.

What happens when that "version counter" wraps around?

;^)
 
M

Moshbear dot Net

Perhaps an atomic fetch-and-add operation, or a statically initialized
PThread mutex.

Is there a portable way of doing
atomic {
++xctr;
ctr = xctr;
}

Also, it looks like I'm going to have to search the boost docs for
mutex-locked statically-scoped counters.
However, I believe that somebody has already done this and can offer
guidance as to which boost class is
preferred (or c++0x/tr1 class, given that this is c.l.c++ :)
What happens when that "version counter" wraps around?

I'd be using ::uint64_t in actual code. This was just to show the
concept.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,233
Latest member
AlyssaCrai

Latest Threads

Top