在C++中,静态全局变量在多线程环境下的表现主要涉及到线程安全和初始化顺序问题。
#include <iostream>
#include <mutex>
std::mutex mtx;
int static_global_var = 0;
void thread_function() {
std::lock_guard<std::mutex> lock(mtx);
static_global_var++;
}
int main() {
std::thread t1(thread_function);
std::thread t2(thread_function);
t1.join();
t2.join();
std::cout << "Static global variable: " << static_global_var << std::endl;
return 0;
}
#include <iostream>
void thread_function() {
static int static_global_var = 0;
static_global_var++;
}
int main() {
std::thread t1(thread_function);
std::thread t2(thread_function);
t1.join();
t2.join();
std::cout << "Static global variable: " << static_global_var << std::endl;
return 0;
}
std::call_once
和std::once_flag
:这些函数可以确保给定的函数只被调用一次,从而保证初始化顺序的正确性。#include <iostream>
#include <mutex>
std::once_flag flag;
int static_global_var = 0;
void initialize_static_global_var() {
static_global_var = 0;
}
void thread_function() {
std::call_once(flag, initialize_static_global_var);
static_global_var++;
}
int main() {
std::thread t1(thread_function);
std::thread t2(thread_function);
t1.join();
t2.join();
std::cout << "Static global variable: " << static_global_var << std::endl;
return 0;
}
总之,在多线程环境下使用静态全局变量时,需要注意线程安全和初始化顺序问题,并采取适当的同步策略来确保正确的行为。