21xrx.com
2025-07-03 13:21:12 Thursday
文章检索 我的文章 写文章
C++实现线程:三种方法详解
2023-07-04 18:07:38 深夜i     13     0
C++ 线程 实现方法 详解 三种

在C++中,线程可以使用多种方式实现。本文将详细介绍3种不同的方法:基于函数的线程、基于类的线程和C++11的线程。

1. 基于函数的线程

使用基于函数的线程,可以利用C语言中的线程库来实现线程。基于函数的线程通常会使用pthread_create函数来创建一个线程。在创建线程时,需要传递一个函数指针,当线程创建完成后,线程将运行该函数。示例代码如下:

#include <iostream>
#include <pthread.h>
using namespace std;
void* threadFunc(void* arg)
  cout << "Thread running" << endl;
  return NULL;
int main() {
  pthread_t threadId;
  pthread_create(&threadId, NULL, threadFunc, NULL);
  pthread_join(threadId, NULL);
  cout << "Thread joined" << endl;
  return 0;
}

2. 基于类的线程

使用基于类的线程可以更方便地利用C++中的面向对象特性来实现线程。该方法需要创建一个继承自std::thread类的自定义类,并实现该类的run方法。示例代码如下:

#include <iostream>
#include <thread>
using namespace std;
class MyThread : public thread {
  public:
    void run()
      cout << "Thread running" << endl;
    
};
int main() {
  MyThread threadObj;
  threadObj.start();
  threadObj.join();
  cout << "Thread joined" << endl;
  return 0;
}

3. C++11的线程

C++11提供了一种更高级的线程实现方式,可以更方便地创建和管理线程。可以使用std::thread类的构造函数来创建一个线程,并使用join方法等待线程的完成。示例代码如下:

#include <iostream>
#include <thread>
using namespace std;
void threadFunc()
  cout << "Thread running" << endl;
int main() {
  thread threadObj(threadFunc);
  threadObj.join();
  cout << "Thread joined" << endl;
  return 0;
}

总的来说,以上3种实现线程的方法各有优劣。选择哪种方法应基于具体应用场景和需求进行选择,以获得最佳的线程效率和应用性能。

  
  

评论区