C++11引入了标准库中的多线程支持,包括std::thread类和各种同步机制
互斥锁std::mutex : 互斥锁用于保护共享资源,确保同一时间只有一个线程能够访问该资源,以防止数据竞争。
条件变量std::condition_variable : 条件变量用于线程之间的通信,允许一个或多个线程等待某个条件(或者事件)的发生,而另一个线程则可以通知这些等待的线程该条件已经满足。
原子操作std::atomic : 原子操作用于无锁编程,提供对基本数据类型的原子读写操作,防止数据竞争而无需显式的锁机制。
信号量(Semaphore):用于控制对共享资源的访问,可以实现多个线程之间的同步和互斥。
读写锁(Reader-Writer Lock):用于实现读写线程对共享数据的访问控制,允许多个读线程同时进行读操作,但只允许一个写线程进行写操作。
屏障(Barrier):用于保证多个线程在某个点上同步,只有当所有线程都达到屏障点时才能继续执行。
事件(Event):用于实现线程间的通信和同步,一个线程等待某个事件的发生,而另一个线程触发该事件。
互斥量递归锁(Recursive Mutex):与互斥锁类似,但允许同一个线程多次获得同一个锁,避免死锁。
读写互斥量(Read-Write Mutex):类似于读写锁,但使用互斥量来实现,可以更灵活地控制读写线程对共享数据的访问。
创建和管理线程
#include <iostream>
#include <thread>void printMessage(const std::string& message) {std::cout << message << std::endl;
}int main() {std::thread t1(printMessage, "Hello from thread 1");std::thread t2(printMessage, "Hello from thread 2");// 等待线程结束t1.join();t2.join();return 0;
}
使用互斥锁进行同步
#include <iostream>
#include <thread>
#include <mutex>std::mutex mtx;void printMessage(const std::string& message) {std::lock_guard<std::mutex> lock(mtx);std::cout << message << std::endl;
}int main() {std::thread t1(printMessage, "Hello from thread 1");std::thread t2(printMessage, "Hello from thread 2");t1.join();t2.join();return 0;
}
使用条件变量进行线程间通信
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>std::mutex mtx;
std::condition_variable cv;
bool ready = false;void printMessage() {std::unique_lock<std::mutex> lock(mtx);cv.wait(lock, []{ return ready; });std::cout << "Hello from thread!" << std::endl;
}int main() {std::thread t(printMessage);{std::lock_guard<std::mutex> lock(mtx);ready = true;}cv.notify_one();t.join();return 0;
}
信号量(Semaphore):
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <semaphore.h>sem_t semaphore;void worker() {sem_wait(&semaphore); // 等待信号量std::cout << "执行任务" << std::endl;
}int main() {sem_init(&semaphore, 0, 0); // 初始化信号量为0std::thread t(worker);// 模拟一些操作std::this_thread::sleep_for(std::chrono::seconds(2));sem_post(&semaphore); // 发送信号量t.join();sem_destroy(&semaphore);return 0;
}
读写锁(Reader-Writer Lock):
#include
#include <thread>
#include <shared_mutex>std::shared_mutex rwMutex;
int data = 0;void reader() {std::shared_lock<std::shared_mutex> lock(rwMutex);std::cout << "读取数据:" << data << std::endl;
}void writer() {std::unique_lock<std::shared_mutex> lock(rwMutex);data++;std::cout << "写入数据:" << data << std::endl;
}int main() {std::thread readerThread1(reader);std::thread readerThread2(reader);std::thread writerThread(writer);readerThread1.join();readerThread2.join();writerThread.join();return 0;
}
屏障(Barrier):
#include <iostream>
#include <thread>
#include <barrier>std::barrier myBarrier(3); // 创建一个屏障,需要三个线程都到达后才能继续执行void worker() {// 模拟一些操作std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "执行任务" << std::endl;myBarrier.arrive_and_wait(); // 到达屏障并等待std::cout << "任务完成" << std::endl;
}int main() {std::thread t1(worker);std::thread t2(worker);std::thread t3(worker);t1.join();t2.join();t3.join();return 0;
}
事件(Event)
事件可以用于实现线程间的通信和同步,一个线程等待某个事件的发生,而另一个线程触发该事件。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>std::mutex mtx;
std::condition_variable cv;
bool eventOccurred = false;void waitForEvent() {std::unique_lock<std::mutex> lock(mtx);while (!eventOccurred) {cv.wait(lock);}std::cout << "事件已发生,执行任务" << std::endl;
}void triggerEvent() {{std::lock_guard<std::mutex> lock(mtx);eventOccurred = true;}cv.notify_one();std::cout << "事件已触发" << std::endl;
}int main() {std::thread t1(waitForEvent);std::this_thread::sleep_for(std::chrono::seconds(2));std::thread t2(triggerEvent);t1.join();t2.join();return 0;
}
互斥量递归锁(Recursive Mutex)
互斥量递归锁允许同一个线程多次获得同一个锁,避免了死锁。
#include <iostream>
#include <thread>
#include <mutex>std::recursive_mutex mtx;void recursiveFunction(int depth) {std::lock_guard<std::recursive_mutex> lock(mtx);if (depth > 0) {std::cout << "递归深度:" << depth << std::endl;recursiveFunction(depth - 1);}
}int main() {recursiveFunction(3);return 0;
}
读写互斥量(Read-Write Mutex)
读写互斥量使用互斥量来实现,可以更灵活地控制读写线程对共享数据的访问。
#include <iostream>
#include <thread>
#include <mutex>std::mutex readMutex;
std::mutex writeMutex;
int data = 0;void reader() {std::lock_guard<std::mutex> lock(readMutex);std::cout << "读取数据:" << data << std::endl;
}void writer() {std::lock_guard<std::mutex> lock(writeMutex);data++;std::cout << "写入数据:" << data << std::endl;
}int main() {std::thread readerThread1(reader);std::thread readerThread2(reader);std::thread writerThread(writer);readerThread1.join();readerThread2.join();writerThread.join();return 0;
}