阅读量:2
在Linux下使用C++实现并发,主要有以下几种方式:
1. 多线程(Multithreading)
C++11引入了标准库中的头文件,提供了创建和管理线程的功能。
示例代码:
#include
#include
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join(); // 等待线程完成
return 0;
}
2. 异步编程(Asynchronous Programming)
C++11还引入了和头文件,用于异步编程。
示例代码:
#include
#include
int asyncFunction() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, asyncFunction);
std::cout << "Waiting for the result..." << std::endl;
int value = result.get(); // 获取结果,阻塞直到结果可用
std::cout << "Result: " << value << std::endl;
return 0;
}
3. 进程间通信(Inter-Process Communication, IPC)
Linux提供了多种IPC机制,如管道(pipes)、消息队列(message queues)、共享内存(shared memory)和信号量(semaphores)。
示例代码(使用管道):
#include
#include
#include
#include
int main() {
int pipefd[2];
pid_t pid = fork();
if (pid == 0) { // 子进程
close(pipefd[0]); // 关闭读端
char buffer[] = "Hello from child!";
write(pipefd[1], buffer, sizeof(buffer));
close(pipefd[1]);
} else if (pid > 0) { // 父进程
close(pipefd[1]); // 关闭写端
char buffer[100];
read(pipefd[0], buffer, sizeof(buffer));
std::cout << "Message from child: " << buffer;
close(pipefd[0]);
wait(NULL); // 等待子进程结束
} else {
std::cerr << "Fork failed!" << std::endl;
return 1;
}
return 0;
}
4. 使用第三方库
还有一些第三方库可以帮助实现并发,例如Boost.Asio、libuv等。
示例代码(使用Boost.Asio):
#include
#include
using boost::asio::ip::tcp;
void session(tcp::socket sock) {
try {
for (;;) {
char data[1024];
boost::system::error_code error;
size_t length = sock.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
boost::asio::write(sock, boost::asio::buffer(data, length));
}
} catch (std::exception& e) {
std::cerr << "Exception in thread: " << e.what() << std::endl;
}
}
int main() {
try {
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 12345));
for (;;) {
tcp::socket socket(io_context);
acceptor.accept(socket);
std::thread(session, std::move(socket)).detach();
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
总结
- 多线程:适用于需要在同一进程中并发执行多个任务的场景。
- 异步编程:适用于需要非阻塞操作的场景,可以提高程序的响应性。
- 进程间通信:适用于需要在不同进程之间共享数据或通信的场景。
- 第三方库:提供了更高级的并发编程抽象和功能。
选择哪种方式取决于具体的应用需求和场景。
以上就是关于“C++ Linux下怎样实现并发”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm