在Linux中,C++可以通過多種方式實現并發。以下是一些常見的方法:
<thread>
庫可以輕松地創建和管理線程。#include <iostream>
#include <thread>
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join(); // 等待線程完成
return 0;
}
<future>
和<async>
庫可以執行異步任務,并且可以獲取它們的結果。#include <iostream>
#include <future>
int add(int x, int y) {
return x + y;
}
int main() {
std::async(std::launch::async, add, 5, 7); // 異步執行add函數
// 可以繼續執行其他操作
// ...
std::future<int> result = std::async(std::launch::async, add, 5, 7).get(); // 獲取結果
std::cout << "The result is " << result << std::endl;
return 0;
}
<mutex>
庫可以保護共享資源,防止多個線程同時訪問。#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 創建一個互斥鎖
void printMessage(const std::string& msg) {
mtx.lock(); // 鎖定互斥鎖
std::cout << msg << std::endl;
mtx.unlock(); // 解鎖互斥鎖
}
int main() {
std::thread t1(printMessage, "Hello from thread 1");
std::thread t2(printMessage, "Hello from thread 2");
t1.join();
t2.join();
return 0;
}
<condition_variable>
庫可以在多線程之間同步狀態。#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void printId(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(printId, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
信號量:雖然C++標準庫沒有直接提供信號量的實現,但是可以使用POSIX信號量(semaphore.h
)或者Boost庫中的信號量。
管道和命名管道:使用<sys/types.h>
、<sys/stat.h>
、<fcntl.h>
、<unistd.h>
等系統頭文件可以實現進程間通信(IPC),包括管道和命名管道。
消息隊列:同樣使用系統頭文件,可以實現消息隊列來進行進程間通信。
共享內存:使用<sys/ipc.h>
、<sys/shm.h>
等系統頭文件可以實現共享內存,允許多個進程訪問同一塊內存區域。
套接字:使用<sys/socket.h>
、<netinet/in.h>
、<arpa/inet.h>
等系統頭文件可以實現網絡編程,包括TCP和UDP套接字。
選擇哪種并發模型取決于具體的應用場景和需求。多線程和異步任務通常用于提高程序的執行效率,而互斥鎖、條件變量等同步機制則用于保證線程安全。