Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

To mutex or not to mutex an int global variable ??

global int mutex
0
Posted

To mutex or not to mutex an int global variable ??

0

Frank, Nice *idea*, but no marbles. 🙁 Lots of variations of this idea are proposed regularly, starting with Dekker’s algorithm and going on and on. The problem is that you are assuming that writes from the CPU are arriving in main memory in order. They may not. On all high performance CPUs today (SPARC, Alpha, PA-RISC, MIPS, x86, etc.) out-of-order writes are allowed. Hence in your example below, it is POSSIBLE that only one of the values will be updated before the pointer is swapped. Bummer, eh? -Bil “Use the mutex, Luke!” > To avoid locks you might try the following trick: > Replace the two ints by a struct that contains total and fraction. The global > variable would then be a pointer to the struct. To modify the variables, the writer > would use a temporary struct, update the value(s) and then swap the pointers of the > global pointer and the temporary global pointer. This works assuming that a pointer > write is an atomic operation (which is the case in all architectures I know)

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123