阅读量:2
在Linux中进行C++并发编程,通常有以下几种方法:
1. POSIX Threads (pthreads)
POSIX Threads是Linux上实现线程的标准库。
示例代码:
#include
#include
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return nullptr;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Failed to create thread" << std::endl;
return 1;
}
pthread_join(thread, nullptr);
return 0;
}
编译:
g++ -pthread your_program.cpp -o your_program
2. C++11 Standard Library Threads
C++11引入了标准库线程支持,提供了更高级和更方便的接口。
示例代码:
#include
#include
void thread_function() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread t(thread_function);
t.join();
return 0;
}
编译:
g++ -std=c++11 your_program.cpp -o your_program
3. C++11 Future and Promise
std::future和std::promise用于线程间的同步和数据传递。
示例代码:
#include
#include
#include
void thread_function(std::promise<int> prom) {
std::this_thread::sleep_for(std::chrono::seconds(1));
prom.set_value(42);
}
int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread t(thread_function, std::move(prom));
std::cout << "Waiting for thread to finish..." << std::endl;
int result = fut.get();
std::cout << "Thread returned: " << result << std::endl;
t.join();
return 0;
}
编译:
g++ -std=c++11 your_program.cpp -o your_program
4. C++11 Async
std::async提供了一种更高级的方式来启动异步任务,它会自动管理线程的创建和销毁。
示例代码:
#include
#include
int async_function() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 42;
}
int main() {
std::future<int> fut = std::async(std::launch::async, async_function);
std::cout << "Waiting for async function to finish..." << std::endl;
int result = fut.get();
std::cout << "Async function returned: " << result << std::endl;
return 0;
}
编译:
g++ -std=c++11 your_program.cpp -o your_program
5. C++20 Coroutines
C++20引入了协程,提供了一种更高级的并发编程模型。
示例代码:
#include
#include
struct Task {
struct promise_type {
Task get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
Task async_function() {
std::cout << "Async function started" << std::endl;
co_await std::suspend_never{};
std::cout << "Async function resumed" << std::endl;
}
int main() {
async_function();
return 0;
}
编译:
g++ -std=c++20 your_program.cpp -o your_program
总结
- POSIX Threads (pthreads):适用于需要底层控制的场景。
- C++11 Standard Library Threads:提供了更现代和安全的接口。
- C++11 Future and Promise:适用于线程间的同步和数据传递。
- C++11 Async:提供了一种更高级的异步任务管理方式。
- C++20 Coroutines:提供了更高级的并发编程模型。
选择哪种方法取决于你的具体需求和项目的复杂性。
以上就是关于“C++在Linux中如何进行并发编程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm