您好,登錄后才能下訂單哦!
在 Linux C++ 項目中實現線程間的異步通信,可以使用以下幾種方法:
std::mutex
類來實現互斥鎖。#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥鎖
void thread_func() {
mtx.lock(); // 加鎖
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
mtx.unlock(); // 解鎖
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
t1.join();
t2.join();
return 0;
}
std::condition_variable
類來實現條件變量。#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void thread_func() {
std::unique_lock<std::mutex> lock(mtx); // 加鎖
cv.wait(lock, []{ return ready; }); // 等待條件變量
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
{
std::lock_guard<std::mutex> lock(mtx); // 加鎖
ready = true; // 設置條件變量
}
cv.notify_all(); // 通知所有等待的線程
t1.join();
t2.join();
return 0;
}
std::pipe
類來實現管道。#include <iostream>
#include <thread>
#include <vector>
#include <unistd.h>
int pipe_fd[2];
void thread_func(int fd) {
char buffer[1024];
read(fd, buffer, sizeof(buffer)); // 從管道讀取數據
std::cout << "Thread ID: " << std::this_thread::get_id() << " received: " << buffer << std::endl;
}
int main() {
if (pipe(pipe_fd) == -1) {
std::cerr << "Error creating pipe" << std::endl;
return 1;
}
std::thread t1(thread_func, pipe_fd[0]);
std::thread t2(thread_func, pipe_fd[0]);
write(pipe_fd[1], "Hello from main thread!", strlen("Hello from main thread!")); // 向管道寫入數據
close(pipe_fd[1]);
t1.join();
t2.join();
close(pipe_fd[0]);
return 0;
}
Boost.Interprocess
庫來實現消息隊列。#include <iostream>
#include <thread>
#include <boost/interprocess/ipc/message_queue.hpp>
boost::interprocess::message_queue mq;
void thread_func() {
const char* message = "Hello from thread!";
mq.send(message, strlen(message), 0); // 發送消息到消息隊列
}
int main() {
mq.open("my_message_queue", boost::interprocess::open_or_create, 65536); // 打開或創建消息隊列
std::thread t1(thread_func);
std::thread t2(thread_func);
char buffer[65536];
size_t received_size = mq.receive(buffer, sizeof(buffer), 0); // 從消息隊列接收消息
std::cout << "Thread ID: " << std::this_thread::get_id() << " received: " << buffer << std::endl;
mq.close(); // 關閉消息隊列
t1.join();
t2.join();
return 0;
}
這些方法可以根據項目需求選擇使用。互斥鎖和條件變量適用于線程間的同步通信,而管道和消息隊列適用于線程間的異步通信。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。