Linux中C++程序如何實現多線程

在#%#$#%@%@%$#%$#%#%#$%@_e206a54e97690c++e50cc872dd70ee896系統中,c++程序可以采用多種方式來實現線程功能。以下是兩種常見的實現方法:

方法一:利用POSIX線程(pthreads)庫

POSIX線程庫(pthreads)是unix-like操作系統(包括linux)中廣泛應用的多線程庫。

示例代碼:

#include <iostream> #include <pthread.h> <p>// 線程函數 void<em> thread_function(void</em> arg) { int thread_id = <em>(static_cast<int</em>>(arg)); std::cout << "Thread ID: " << thread_id << std::endl; return nullptr; }</p><p>int main() { pthread_t threads[5]; int thread_ids[5] = {1, 2, 3, 4, 5};</p><pre class="brush:php;toolbar:false">for (int i = 0; i < 5; ++i) {     pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]); }  for (int i = 0; i < 5; ++i) {     pthread_join(threads[i], nullptr); }  return 0;

}

編譯與運行:

g++ -pthread -o multithread_example multithread_example.cpp ./multithread_example

方法二:使用C++11標準庫中的頭文件

C++11標準引入了頭文件,使得多線程編程更加直觀和簡便。

示例代碼:

#include <iostream> #include <thread> #include <vector> <p>// 線程函數 void thread_function(int thread_id) { std::cout << "Thread ID: " << thread_id << std::endl; }</p><p>int main() { std::vector<std::thread> threads;</p><pre class="brush:php;toolbar:false">for (int i = 0; i < 5; ++i) {     threads.emplace_back(thread_function, i + 1); }  for (auto& thread : threads) {     thread.join(); }  return 0;

}

編譯與運行:

g++ -std=c++11 -pthread -o multithread_example multithread_example.cpp ./multithread_example

總結

  • POSIX線程(pthreads):適合需要跨平臺兼容性的項目,但需要手動管理線程的生命周期。
  • C++11標準庫中的:提供更加現代和簡潔的多線程編程接口,推薦在C++11及以上版本中使用。

具體選擇哪種方法應根據項目需求和環境來決定。

Linux中C++程序如何實現多線程

立即學習C++免費學習筆記(深入)”;

? 版權聲明
THE END
喜歡就支持一下吧
點贊11 分享