Class members locking

I need two modify two class members (the same class instance) by 2 threads, each of the thread will access a different member variable, the two threads will never access the same member variable. I found a page that talks about this issue:,+provide+a+mutex+and+guarantee+no+adjacent+data+is+also+accessed


Is this true for C++ and classes, do i need to lock the entire class (use one critical section to lock the entire class), can i use different critical sections to lock each of the variables (each member has it's own critical section)?

If you don't use bitfield, you are safe to access different variable in different thread.

Of course for shared variable, you need to use some locking.

It depends on alignment, CPU word size, etc. The risk is low for 32-bit values, but keep them separated to be sure.

But just as important is the fact that if you have threads on different cores repeatedly hitting memory in the same cache-line, then you're going to get terrible performance problems. When you have multiple cores, it's best to make sure they're working with totally different areas of memory.