在Linux中进行C++并发编程,通常有以下几种方法:
POSIX Threads是Linux上实现线程的标准库。
示例代码:
#include <pthread.h>
#include <iostream>
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
C++11引入了标准库线程支持,提供了更高级和更方便的接口。
示例代码:
#include <thread>
#include <iostream>
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
std::future
和std::promise
用于线程间的同步和数据传递。
示例代码:
#include <thread>
#include <future>
#include <iostream>
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
std::async
提供了一种更高级的方式来启动异步任务,它会自动管理线程的创建和销毁。
示例代码:
#include <future>
#include <iostream>
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
C++20引入了协程,提供了一种更高级的并发编程模型。
示例代码:
#include <coroutine>
#include <iostream>
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
选择哪种方法取决于你的具体需求和项目的复杂性。