在Linux下使用C++实现并发,主要有以下几种方式:
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; }
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; }
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; }
还有一些第三方库可以帮助实现并发,例如Boost.Asio、libuv等。
#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; }
选择哪种方式取决于具体的应用需求和场景。