在 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。