温馨提示×

C++ Linux下怎样实现并发

小樊
47
2025-06-23 20:59:42
栏目: 编程语言

在Linux下使用C++实现并发,主要有以下几种方式:

1. 多线程(Multithreading)

C++11引入了标准库中的<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; } 

2. 异步编程(Asynchronous Programming)

C++11还引入了<future><async>头文件,用于异步编程。

示例代码:

#include <iostream> #include <future> 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 <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> 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 <iostream> #include <boost/asio.hpp> 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; } 

总结

  • 多线程:适用于需要在同一进程中并发执行多个任务的场景。
  • 异步编程:适用于需要非阻塞操作的场景,可以提高程序的响应性。
  • 进程间通信:适用于需要在不同进程之间共享数据或通信的场景。
  • 第三方库:提供了更高级的并发编程抽象和功能。

选择哪种方式取决于具体的应用需求和场景。

0