在Linux系统中,C++可以通过多种方式实现并发编程。以下是一些常用的方法:
POSIX Threads(pthreads)是Linux系统上最常用的线程库。
包含头文件:
#include <pthread.h>
定义线程函数:
void* thread_function(void* arg) {
// 线程执行的代码
return NULL;
}
创建线程:
pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, thread_function, NULL);
if (result != 0) {
// 处理错误
}
等待线程结束:
pthread_join(thread_id, NULL);
销毁线程:
pthread_exit(NULL);
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return NULL;
}
int main() {
pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, thread_function, NULL);
if (result != 0) {
std::cerr << "Error creating thread" << std::endl;
return 1;
}
pthread_join(thread_id, NULL);
std::cout << "Thread finished" << std::endl;
return 0;
}
C++11引入了标准库中的线程支持,使得并发编程更加方便和跨平台。
包含头文件:
#include <thread>
定义线程函数:
void thread_function() {
// 线程执行的代码
}
创建线程:
std::thread t(thread_function);
等待线程结束:
t.join();
分离线程(可选):
t.detach();
#include <iostream>
#include <thread>
void thread_function() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread t(thread_function);
t.join();
std::cout << "Thread finished" << std::endl;
return 0;
}
C++11还提供了std::async来执行异步任务,它会自动管理线程的创建和销毁。
包含头文件:
#include <future>
定义异步任务:
std::future<void> result = std::async(std::launch::async, []() {
// 异步任务代码
});
获取结果:
result.get();
#include <iostream>
#include <future>
int main() {
auto result = std::async(std::launch::async, []() {
std::cout << "Async task is running" << std::endl;
});
result.get();
std::cout << "Async task finished" << std::endl;
return 0;
}
C++11及以后的版本还提供了一些并发容器和算法,如std::atomic、std::mutex、std::lock_guard等,用于更复杂的并发控制。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void print_block(int n, char c) {
std::lock_guard<std::mutex> guard(mtx);
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
通过这些方法,你可以在Linux系统中使用C++进行高效的并发编程。选择哪种方法取决于你的具体需求和项目的复杂性。