bobobobo
bobobobo

Reputation: 67286

Do I have to mark complex types as `volatile` if I am locking around the variable?

I'm using pthread_mutex_t locks to "lock around" a complex typed variable a (std::list). I say "lock around" because pthread_mutex_lock() doesn't use the actual the std::list variable as C#'s lock does. So the std::list object has no idea it is being locked for access.

So I really don't know the answer to 2 questions:

1) Does marking a complex type as volatile (other than int, float etc) have any effect in C++? I am not sure since the above linked article lists (which for C#) only the primitive types and reference types as capable of being marked volatile.

2) Do I need to mark C++ complex types as volatile as long as I am manually locking them?

Upvotes: 2

Views: 254

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308432

The volatile keyword tells the compiler that a variable might be changing via some mechanism outside of the current thread and so it shouldn't optimize away seemingly redundant accesses. It means nothing more, although some compilers may give it additional meaning - the Microsoft Visual C++ compiler has this to say:

Although the processor does not reorder un-cacheable memory accesses, un-cacheable variables must be marked as volatile to guarantee that the compiler does not reorder the memory accesses.

The mutex code will probably provide the necessary memory fence to ensure that the reads and writes to the protected variable don't extend beyond the bounds of the mutex, so I'd say that marking it volatile would not be necessary - if you've properly implemented the mutex there is no chance that another thread could try to access it.

Upvotes: 1

Related Questions