2

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?

bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 2
    `volatile` simply means that access to this variable is observable and cannot be optimized away, IIRC. It does not mean thread safe, synchronized, or whatever else. Some implementations have implementation specific meanings attached to it. C++11 adds some threading and sychronization support to the language, prior to that it was ad hoc and library specific. – Yakk - Adam Nevraumont May 29 '13 at 01:40
  • 2
    Related: http://stackoverflow.com/q/2484980/335858, http://stackoverflow.com/q/4557979/335858. Very related: http://stackoverflow.com/q/3208060/335858 – Sergey Kalinichenko May 29 '13 at 01:40

1 Answers1

1

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622