gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
c++程序怎么并发 linux下
- User
c++程序怎么并发 linux下
- Assistant
在Linux下实现C++的并发可以使用多线程或多进程来实现。下面分别介绍两种方法:
- 多线程:
使用C++的线程库来实现多线程编程。我们可以使用标准库中的
<thread>和<mutex>等头文件来实现多线程。
#include <iostream> #include <thread> void my_func() { // 线程执行的代码 std::cout << "Hello from thread! Thread ID: " << std::this_thread::get_id() << std::endl; } int main() { // 创建一个线程 std::thread t(my_func); // 主线程执行的代码 std::cout << "Hello from main! Thread ID: " << std::this_thread::get_id() << std::endl; // 等待线程执行完毕 t.join(); return 0; }上述代码中,我们使用
std::thread类来创建了一个新的线程,并在my_func函数中定义了线程执行的代码。在main函数中,我们也输出了当前线程的ID。- 多进程: 使用Linux系统调用来创建多个进程,每个进程可以独立运行。
#include <iostream> #include <unistd.h> int main() { pid_t pid = fork(); // 创建一个新的进程 if (pid < 0) { std::cerr << "Fork failed!" << std::endl; return 1; } else if (pid == 0) { // 子进程执行的代码 std::cout << "Hello from child! Process ID: " << getpid() << std::endl; } else { // 父进程执行的代码 std::cout << "Hello from parent! Child process ID: " << pid << std::endl; } return 0; } - 多线程:
使用C++的线程库来实现多线程编程。我们可以使用标准库中的
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.