- std::atomic
std::atomic提供了一种原子类型,可以在多线程中进行原子操作。
示例代码:
#include <atomic>
#include <thread>
std::atomic<int> count(0);
void increment() {
for (int i = 0; i < 100000; i++) {
count++;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Count: " << count << std::endl;
return 0;
}
- std::mutex
std::mutex提供了一种互斥量,可以在多线程中对共享资源进行加锁和解锁。
示例代码:
#include <mutex>
#include <thread>
std::mutex mtx;
int count = 0;
void increment() {
for (int i = 0; i < 100000; i++) {
mtx.lock();
count++;
mtx.unlock();
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Count: " << count << std::endl;
return 0;
}
- std::atomic_flag
std::atomic_flag提供了一种原子布尔类型,可以在多线程中进行原子操作。
示例代码:
#include <atomic>
#include <thread>
std::atomic_flag flag = ATOMIC_FLAG_INIT;
int count = 0;
void increment() {
for (int i = 0; i < 100000; i++) {
while (flag.test_and_set(std::memory_order_acquire)) {}
count++;
flag.clear(std::memory_order_release);
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Count: " << count << std::endl;
return 0;
}
- std::atomic_exchange
std::atomic_exchange提供了一种原子交换操作,可以在多线程中进行原子操作。
示例代码:
#include <atomic>
#include <thread>
std::atomic<int> count(0);
void increment() {
for (int i = 0; i < 100000; i++) {
int expected = count.load();
while (!count.compare_exchange_weak(expected, expected + 1));
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Count: " << count << std::endl;
return 0;
}