Is it thread safe to change a variable with no calculation of previous data involved?

I heard it's thread unsafe to do "global_variable += individual_thread_data"; for example [without locks].

But is it thread safe if one only does "global_variable = individual_thread_data" in each thread?


Without considering the variable type, it is not thread safe. You should use mutexes/critical sections or atomic variables.

Sometimes it useful to write a simple code which assigns variables of several types and disassemble it to see how it is going to be assigned.

Also, for a cas-supporting architecture you can use assembler code to simulate an atomic variable.

(Another tip: the variable should be declared as volatile if used in threads, to prevent the optimization done by compiler.)

No, it's just as unsafe (another thread may be using that variable at the same time).

Need Your Help

Why are there two overloads for vector::push_back?

c++ c++11

Why doesn't vector::push_back take a forwarding reference instead of having two overloads? I've read that the only reason you'd want to overload on lvalues and rvalues is if your functions do somet...

myVariable(int) == 0 same as myVariable(Guid) == Guid.Empty

c# .net guid uniqueidentifier equality

I recently converted a bunch of tables PK's from int to uniqueidentifier. Now in my code I am replacing certain checks like so:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.