Reputation:
I need to protect the assignment or initialization of a const variable using lock. Something like this:
int device_write() {
/* ... */
lock (lock);
const int var = test_variable[INDEX];
/* ... */
...
/* var being used here sometime later*/
unlock(lock)
...
}
But now the compiler starts giving warning that declaration is after statement. Becasue the const int var = ..
declaration is below spin_lock().
The var
variable is not a global variable.
Actually the Right hand side of assignment is pretty big in real code. So want to capture that first in variable named var and use it later in a complex statement involving var with various bit operation. That is the requirement. Cant change that
Basically on the right hand side of the assignment the test_variable[..]
is vulnerable to race condition due to concurrency/multithreading. Hence a lock() is needed for protection.
Is there any other elegant way around to achieve that?
Upvotes: 1
Views: 85
Reputation: 26753
You only need to separate the definition of the variable from the write access that needs protection, especially as the part which writes to the left (by your own statement) is not the point.
To make sure that the variable does not get a value from an inconsistent read, it is enough to do the reading inside the lock, which in turn does not need to be at initialisation, which was what annoyed the compiler.
So:
int some_function()
{
/* ... */
int nonconst = 0; /* no declaration is after statement */
lock ( ...)
nonconst = test_variable[INDEX]; /* only assignment, no declaration */
/* ... */
{ /* start a new block to solve the compilers sequence complaint */
const int var = nonconst; /* var itself is const */
/* ... */
/* var being used sometime later, no code can change var */
/* changing the nonconst variable is possible, but does not affect
the value of var anymore */
/* ... */
}
unlock(...)
}
Above is my answer, please find below a more elegant version, which I understand was derived by OP from the insightful comment of Adrian Mole (which I blindly missed...) and the structure of my answer. Should Adrian or OP make their own answer and notify me, I will delete this part. For the time being it improves this answer, for the benefit of others.
int some_function()
{
/* ... */
lock ( ...);
{ /* start a new block to solve the compilers sequence complaint */
const int var = test_variable[INDEX]; /* var itself is const */
/* ... */
/* var being used sometime later, no code can change var */
/* ... */
}
unlock(...);
}
I did some tiny edits to reduce confusion and compiler warnings a little.
Upvotes: 2