المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Multithreaded code and the volatile qualifier



C++ Programming
05-07-2009, 11:50 PM
I have written a multithreaded application, and am wondering if I need to declare any of the shared variables as volatile. I have searched online for a while, but have thus far found no definitive source on when you need to use this qualifier. My code operates similarly to the following:

#include
#define ITER_COUNT 300
#define BUFF_SIZE 10

class Buffer {
public:
const size_t length;
const HANDLE canWrite;
const HANDLE canRead ;
double* data ;
size_t writeIdx;
size_t readIdx ;

Buffer(size_t maxSize) :
data(new double[maxSize]()),
writeIdx(0), readIdx(0), length(maxSize),
canWrite(CreateSemaphore(NULL, static_cast(maxSize),
static_cast(maxSize), NULL)),
canRead (CreateSemaphore(NULL, 0 ,
static_cast(maxSize), NULL)) { }

virtual ~Buffer() {
delete[] data;
CloseHandle(canWrite);
CloseHandle(canRead );
}
};

void ThreadFunc(void* var) {
Buffer& buffer(*static_cast(var));
for (size_t idx = 0; idx < ITER_COUNT; ++idx) {
WaitForSingleObject(buffer.canWrite, INFINITE);
for (size_t j = 0; j < 5; ++j) {
buffer.data[buffer.writeIdx] += idx + j;
}
ReleaseSemaphore (buffer.canRead, 1, NULL);
buffer.writeIdx = (buffer.writeIdx + 1) % buffer.length;
}
}

void main() {
double result = 0;
Buffer buffer(BUFF_SIZE);
HANDLE threadHandle = (HANDLE)_beginthread(&ThreadFunc, 0, buffer);
for (size_t idx = 0; idx < ITER_COUNT; ++idx) {
WaitForSingleObject(buffer.canRead, INFINITE);
result += buffer.data[buffer.readIdx];
buffer.data[buffer.readIdx] = 0;
ReleaseSemaphore (buffer.canWrite, 1, NULL);
buffer.readIdx = (buffer.readIdx + 1) % buffer.length;
}
}Clearly the const members need not be volatile, and the read/write indices are only read or modified in a single thread, so those are ok. However, do I need to declare the Buffer::data pointer as volatile or not?

I have another multithreaded application that has n > 1 threads, such that each thread modifies some data prior to exiting, but does so within a mutex-protected bit of code. Should this variable be declared as volatile as well? Thank you in advance for any assistance.

Sounds like somebody's got a case of the Mondays

-Jeff

modified on Thursday, May 7, 2009 3:41 PM