我尝试了几种逻辑来处理我的这个问题。
- 使用线程本地存储 (TLS)
#include <iostream>
#include <thread>
void thread_function() {
thread_local int local_var = 0;
local_var++;
std::cout << "Local variable value: " << local_var << std::endl;
}
int main() {
std::thread t1(thread_function);
std::thread t2(thread_function);
t1.join();
t2.join();
return 0;
}
- 应用智能指针
#include <iostream>
#include <memory>
void shared_pointer_example() {
std::shared_ptr<int> sptr(new int(10));
std::shared_ptr<int> sptr2 = sptr; // reference count increased
std::cout << "Shared Pointer value: " << *sptr << std::endl;
}
void unique_pointer_example() {
std::unique_ptr<int> uptr(new int(20));
std::cout << "Unique Pointer value: " << *uptr << std::endl;
// std::unique_ptr<int> uptr2 = uptr; // Error: unique_ptr cannot be copied
}
int main() {
shared_pointer_example();
unique_pointer_example();
return 0;
}
- 实现无锁数据结构
#include <iostream>
#include <atomic>
#include <vector>
#include <thread>
std::atomic<int> atomic_counter(0);
void increment() {
for (int i = 0; i < 1000; ++i) {
atomic_counter++;
}
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(increment);
}
for (auto& t : threads) {
t.join();
}
std::cout << "Atomic Counter: " << atomic_counter.load() << std::endl;
return 0;
}
但实际上,没有一个是直观的,或者足够好到可以真正发挥作用。我该怎么办?
我已经尝试了上面提到的 4 种解决方案