class MyClass
{
// some other stuff
struct Chunk
{
int : sampleData;
}
volatile std::list<Chunk>::iterator _currentWriteChunk;
std::list<Chunk>::iterator _currentReadChunk;
int _currentWriteIndex;
int _currentReadIndex;
}
void MyClass::someFunction
{
// get a copy of the currentWriteChunk
// the next line doesn't compile
// but it does compile if I remove the volatile from _currentWriteChunk's declaration
// If I add volatile to the next line it doesn't help
std::list<MyClass::Chunk>::iterator writeChunkToUse ( _currentWriteChunk );
}
VisualStudio 2005 gives me the error code C2558 (no copy constructor or copy constructor declared "explicit")
Btw. it's no problem assigning a volatile int to a non volatile and vice versa.
What I basically want to do is to create a fifo buffer which is written to by one thread and read from another one.
That's why I wanted to make the iterator volatile.
There are two problems using the const_cast:
* const_cast needs a reference or pointer as a type
* if you cheat with volatile there is no point in using it anyway
Declaring an instance of a list<>::iterator as volatile is rather pointless. It is a complex object that the
compiler will not store in registers and elide reads/writes from/to memory.
Besides, if one thread only ever accesses the currentWriteChunk iterator and the other only ever
accesses the currentReadChunk iterator, then there is no collision at that level, so there is no need
even for any synchronization.
If you find a need for synchronization, then "volatile" will not help you; you will need to use
mutexes, etc.
I wanted to declare them volatile so that the reading thread updates the writePointer when it check's if there is new data.
But it was stupid because the write pointer could have been partially updated by the writing thread and then read by the reading thread.
I now made a singly linked list (using volatile raw pointers) by myself and this works without any mutex as long as only one thread writes and one thread reads.
I would have preferred an already tested solution but couldn't find a lightweight solution.