在Linux中,C++可以通过多种方式来处理并发问题。以下是一些常用的方法:
<thread>
库可以轻松地创建和管理线程。你可以创建多个线程来执行不同的任务,从而实现并发。#include <iostream>
#include <thread>
void print_hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread t1(print_hello);
std::thread t2(print_hello);
t1.join();
t2.join();
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void print_block(int n, char c) {
mtx.lock();
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
mtx.unlock();
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return ready;});
std::cout << "Thread " << id << std::endl;
}
void go() {
std::lock_guard<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main() {
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
<atomic>
库,支持原子操作,这些操作可以在多线程环境中安全地执行,而无需使用互斥锁。#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void increment_counter() {
for (int i = 0; i < 100000; ++i) {
counter++;
}
}
int main() {
std::thread t1(increment_counter);
std::thread t2(increment_counter);
t1.join();
t2.join();
std::cout << "Counter: " << counter << std::endl;
return 0;
}
信号量(Semaphore):虽然C++标准库没有直接提供信号量的实现,但你可以使用POSIX信号量(通过<semaphore.h>
头文件)或者自己实现一个简单的信号量。
读写锁(Read-Write Lock):对于读多写少的场景,可以使用读写锁来提高性能。C++标准库没有直接提供读写锁,但你可以使用POSIX读写锁(通过<pthread.h>
头文件)或者第三方库。
无锁编程(Lock-Free Programming):这是一种高级技术,它避免了使用锁,而是使用原子操作和其他技巧来实现线程安全的代码。
选择哪种方法取决于你的具体需求和应用场景。在设计并发程序时,还需要注意避免死锁、竞态条件和其他并发相关的问题。