<p>I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code:</p>

<p>GlobalVar.property = 11;</p>

<p>(assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time?</p>

[{'answer_id': 72147, 'author': 'Laurie Young', 'author_id': 7473, 'author_profile': 'https://Stackoverflow.com/users/7473', 'pm_score': 1, 'selected': False, 'text': '<p>I would expect the result to be undetermined. As in it would vary from compiler to complier, langauge to language and OS to OS etc. So no, it is not safe</p>\n\n<p>WHy would you want to do this though - adding in a line to obtain a mutex lock is only one or two lines of code (in most languages), and would remove any possibility of problem. If this is going to be two expensive then you need to find an alternate way of solving the problem</p>\n'}, {'answer_id': 72215, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on the work actually done by that statement.  There can still be some cases where Something Bad happens - for example, if a C++ class has overloaded the = operator, and does anything nontrivial within that statement.</p>\n\n<p>I have accidentally written code that did something like this with POD types (builtin primitive types), and it worked fine -- however, it\'s definitely not good practice, and I\'m not confident that it\'s dependable.</p>\n\n<p>Why not just lock the memory around this variable when you use it?  In fact, if you somehow "know" this is the only write statement that can occur at some point in your code, why not just use the value 11 directly, instead of writing it to a shared variable?\n(<strong>edit:</strong> I guess it\'s better to use a constant name instead of the <a href="https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad">magic number</a> 11 directly in the code, btw.)</p>\n\n<p>If you\'re using this to figure out when at least one thread has reached this statement, you could use a semaphore that starts at 1, and is decremented by the first thread that hits it.</p>\n'}, {'answer_id': 72346, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 1, 'selected': False, 'text': '<p>In General, this is not considered a safe thing to do unless your system provides for atomic operation (operations that are guaranteed to be executed in a single cycle).\nThe reason is that while the "C" statement looks simple, often there are a number of underlying assembly operations taking place.</p>\n\n<p>Depending on your OS, there are a few things you could do:  </p>\n\n<ul>\n<li>Take a mutual exclusion semaphore (mutex) to protect access </li>\n<li>in some OS, you can temporarily disable preemption, which guarantees your thread will not swap out.</li>\n<li>Some OS provide a writer or reader semaphore which is more performant than a plain old mutex.</li>\n</ul>\n'}, {'answer_id': 72356, 'author': 'Nicholas Mancuso', 'author_id': 8945, 'author_profile': 'https://Stackoverflow.com/users/8945', 'pm_score': -1, 'selected': False, 'text': "<p>If the operation is atomic, you <em>should</em> be able to get by just fine. But I wouldn't do that in practice. It is better just to acquire a lock on the object and write the value.</p>\n"}, {'answer_id': 72571, 'author': 'Torne', 'author_id': 12345, 'author_profile': 'https://Stackoverflow.com/users/12345', 'pm_score': 3, 'selected': False, 'text': "<p>The problem comes when you read that state back, and do something about it. Writing is a red herring - it is true that as long as this is a single word most environments guarantee the write will be atomic, but that doesn't mean that a larger piece of code that includes this fragment is thread-safe. Firstly, presumably your global variable contained a different value to begin with - otherwise if you know it's always the same, why is it a variable? Second, presumably you eventually <strong>read</strong> this value back again?</p>\n\n<p>The issue is that presumably, you are writing to this bit of shared state for a reason - to signal that something has occurred? This is where it falls down: when you have no locking constructs, there is no implied order of memory accesses at all. It's hard to point to what's wrong here because your example doesn't actually contain the <strong>use</strong> of the variable, so here's a trivialish example in neutral C-like syntax:</p>\n\n<pre><code>int x = 0, y = 0;\n\n//thread A does:\nx = 1;\ny = 2;\nif (y == 2)\n    print(x);\n\n//thread B does, at the same time:\nif (y == 2)\n    print(x);\n</code></pre>\n\n<p>Thread A will always print 1, but it's completely valid for thread B to print 0. The order of operations in thread A is only required to be observable from code executing in thread A - thread B is allowed to see any combination of the state. The writes to x and y may not actually happen in order.</p>\n\n<p>This can happen even on single-processor systems, where most people do not expect this kind of reordering - your compiler may reorder it for you. On SMP even if the compiler doesn't reorder things, the memory writes may be reordered between the caches of the separate processors.</p>\n\n<p>If that doesn't seem to answer it for you, include more detail of your example in the question. Without the use of the variable it's impossible to definitively say whether such a usage is safe or not.</p>\n"}, {'answer_id': 111016, 'author': 'Chris Vest', 'author_id': 13251, 'author_profile': 'https://Stackoverflow.com/users/13251', 'pm_score': -1, 'selected': False, 'text': '<p>Assuming that property will never be assigned anything other than 11, then I don\'t see a reason for assigment in the first place. Just make it a constant then.</p>\n\n<p>Assigment only makes sense when you intend to change the value <em>unless</em> the act of assigment itself has other side effects - like volatile writes have memory visibility side-effects in Java. And if you change state shared between multiple threads, then you need to synchronize or otherwise "handle" the problem of concurrency.</p>\n\n<p>When you assign a value, without proper synchronization, to some state shared between multiple threads, then there\'s no guarantees for when the other threads will see that change. And no visibility guarantees means that it it possible that the other threads will <em>never</em> see the assignt.</p>\n\n<p>Compilers, JITs, CPU caches. They\'re all trying to make your code run as fast as possible, and if you don\'t make any explicit requirements for memory visibility, then they will take advantage of that. If not on your machine, then somebody elses.</p>\n'}, {'answer_id': 111469, 'author': 'teeks99', 'author_id': 17949, 'author_profile': 'https://Stackoverflow.com/users/17949', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s my take on the question.</p>\n\n<p>You have two or more threads running that write to a variable...like a status flag or something, where you only want to know if one or more of them was true.  Then in another part of the code (after the threads complete) you want to check and see if at least on thread set that status... for example</p>\n\n<pre><code>bool flag = false\nthreadContainer tc\nthreadInputs inputs\n\ncheck(input)\n{\n    ...do stuff to input\n    if(success)\n        flag = true\n}\n\nstart multiple threads\nforeach(i in inputs) \n   t = startthread(check, i)\n   tc.add(t)  // Keep track of all the threads started\n\nforeach(t in tc)\n    t.join( )  // Wait until each thread is done\n\nif(flag)\n   print "One of the threads were successful"\nelse\n   print "None of the threads were successful"\n</code></pre>\n\n<p>I believe the above code would be OK, assuming you\'re fine with not knowing which thread set the status to true, and you can wait for all the multi-threaded stuff to finish before reading that flag.  I could be wrong though.  </p>\n'}]
['https://Stackoverflow.com/questions/72116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']