面试题答案
一键面试问题阐述
- 线程安全问题:
static
函数内部的static
变量可能会在多线程环境下出现数据竞争。因为多个线程可能同时访问和修改这些静态变量,导致结果不可预测。例如,假设有一个static
函数用于计数,多个线程同时调用该函数时,可能会出现计数不准确的情况。 - 资源管理问题:如果
static
函数管理一些共享资源(如文件句柄、数据库连接等),在多线程环境下可能会出现资源争用和不正确的资源释放。比如,一个static
函数负责打开和关闭文件,多个线程同时调用可能导致文件被意外关闭或多次打开。
解决方案
使用线程局部存储(Thread - Local Storage,TLS)。在C++ 11中,可以通过thread_local
关键字来实现。thread_local
变量每个线程都有自己独立的实例,避免了多线程间的数据竞争。
代码示例
#include <iostream>
#include <thread>
// 使用thread_local解决static函数中的多线程问题
class Counter {
public:
static int getCount() {
// 使用thread_local确保每个线程有自己独立的计数实例
static thread_local int count = 0;
return ++count;
}
};
void threadFunction() {
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << std::this_thread::get_id() << " count: " << Counter::getCount() << std::endl;
}
}
int main() {
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
return 0;
}
在上述代码中,Counter
类的getCount
函数使用thread_local
修饰静态变量count
。这样每个线程在调用getCount
函数时,都有自己独立的count
实例,从而避免了多线程环境下的数据竞争问题。每个线程的计数相互独立,输出结果可以清晰看到每个线程的计数情况。