Hello! 欢迎来到小浪云!


C++中Linux多线程怎样实现


avatar
小浪云 2025-02-20 81

C++中Linux多线程怎样实现

本文演示如何在Linux系统下的c++环境中,运用POSIX线程库(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. ";     pthread_exit(nullptr); // 线程结束     return nullptr; }  int main() {     const int num_threads = 5;     pthread_t threads[num_threads];     int thread_ids[num_threads];      // 创建线程     for (int i = 0; i < num_threads; ++i) {         thread_ids[i] = i;         if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {             std::cerr << "Failed to create thread " << i << ". ";             return 1;         }     }      // 等待线程结束     for (int i = 0; i < num_threads; ++i) {         pthread_join(threads[i], nullptr);     }      std::cout << "All threads finished. ";     return 0; }

编译运行:使用 g++ -o multi_thread_example multi_thread_example.cpp -pthread 编译,然后执行 ./multi_thread_example。

此示例创建5个线程,每个线程打印其ID。 实际应用中,可能需要考虑线程同步机制(如互斥锁 pthread_mutex_t)以避免竞争条件和数据冲突。

相关阅读