在Linux中,C++多線程可以通過兩種方式實現:使用POSIX線程庫(pthread)或C++11標準庫中的線程支持。
POSIX線程庫是Linux系統上廣泛使用的多線程庫。要使用它,你需要在編譯時鏈接pthread庫。
示例代碼:
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
int thread_id = *(static_cast<int*>(arg));
std::cout << "Thread " << thread_id << " is running." << std::endl;
return nullptr;
}
int main() {
pthread_t threads[5];
int thread_ids[5] = {0, 1, 2, 3, 4};
for (int i = 0; i < 5; ++i) {
if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
std::cerr << "Error creating thread "<< i << std::endl;
return 1;
}
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
編譯命令:
g++ -o multi_thread_example multi_thread_example.cpp -pthread
C++11引入了標準庫中的線程支持,使得在C++中實現多線程變得更加簡單和一致。
示例代碼:
#include <iostream>
#include <thread>
#include <vector>
void thread_function(int thread_id) {
std::cout << "Thread " << thread_id << " is running." << std::endl;
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(thread_function, i);
}
for (auto& t : threads) {
t.join();
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
編譯命令:
g++ -o multi_thread_example multi_thread_example.cpp -std=c++11
這兩種方法都可以實現C++多線程編程。C++11標準庫中的線程支持提供了更簡潔的語法和更好的跨平臺兼容性,因此推薦使用C++11標準庫中的線程支持。