我尝试了几种逻辑来处理我的这个问题。
#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 个解决方案
非常有趣的问题。我过去处理过这个问题,希望与您分享!