question with multi-threaded programming

This is a discussion on question with multi-threaded programming within the C++ Programming forums, part of the General Programming Boards category; will it be dangerous that more than one threads are sharing one variable? what would happened if two or more ...

question with multi-threaded programming

will it be dangerous that more than one threads are sharing one variable? what would happened if two or more threads are trying to operate one variable at the same time? any help would be greatly appreciated~~

On a single processor system, only one thread will be running, whichever thread runs second will set the result. On a multi processor system, both are likely to set the value in their own local cache, whichever cache flushes last will set the value.

> will it be dangerous that more than one threads are sharing one variable?
Variables which can be modified in a single instruction are OK - say an integer

Code:

int shared = 0;

Two threads can read and write that as much as they want, and nothing unusual is going to happen.
...

I have to disagree.
All multithreaded access to variables should be protected by synchronization primitives - here's why.

There are a couple of problems that can arise when using this construct. The compiler is free to optimize (what appears to be) read-only access to memory by placing the memory contents into a CPU register. While one thread uses the value within the register, another thread can change the value within memory which the first thread may never see.
This can be overcome on single x86 processor machines by using the volatile keyword. This tells the compiler to not optimize access to an object (reads and writes go directly to memory).

It is true that reads and writes to aligned, CPU-sized data, on an x86 is an atomic operation. (I've also read that this is only true for PII's or higher.) This is not necessarily true on other CPUs, in which case using volatile doesn't help since a read or write operation could be pre-empted.

On SMP machines, volatile doesn't help the situation either since each processor has it's own memory cache. The processors within an SMP machine are only required to synchronize their caches on a memory barrier. Memory barriers occur when certain instructions are executed.

Using a synchronization primitive/function will typically execute one of these instructions and cause a memory barrier. This is necessary so that any cached modifications to an object on another processor are seen by the current processor.

So in summary, synchronization primitives/functions (which cause memory barriers) should be used in order to implement correct synchronization in all environments.