const
global variable CXX-W2009Global variables are accessible anywhere in the scope of the program even in the threads outside of the main thread, as long as it shares the main process stack.
Using non-const global variables is considered quite risky, as they can lead to data races or contention issues.
Consider passing references to unique values and then merging them as if you need mutable stack of program memory.
Note that const pointers and pointer to const are not the same. You need a global pointer to be entirely const for this lint to be satisfied.
That is, if you are passing a pointer, then you need to make sure that the pointer is a const pointer to a const. (See here for more information.)
const int *p = &x;
// should instead be
const int *const p = &x;
int global_counter = 0;
void foo() {
global_counter += 1;
}
int main() {
global_counter += 1;
std::thread t(foo);
t.join();
}
#include <thread>
int main() {
int global_counter = 1;
int global_counter1 = 0;
std::thread t1([&](){
for (int i = 0; i < 10; i++) {
global_counter1 += 1;
}
});
int global_counter2 = 0;
std::thread t2([&](){
for (int i = 0; i < 10; i++) {
global_counter2 += 1;
}
});
t1.join();
t2.join();
global_counter += global_counter1 + global_counter2;
}