21xrx.com
2024-09-19 09:40:29 Thursday
登录
文章检索 我的文章 写文章
C++开启线程的三种方式:详细介绍及使用方法
2023-07-14 17:09:25 深夜i     --     --
C++ 线程 开启 方法 介绍

C++是一种基于面向对象的高级编程语言,目前被广泛应用于网络开发、游戏制作、桌面应用和数据科学领域等。其中,线程作为C++多线程编程的重要组成部分,可以有效地提升程序的运行效率。本文将详细介绍C++开启线程的三种方式,并提供对应的使用方法,以便读者深入了解和运用。

1. 使用std::thread

std::thread是C++11标准库提供的线程库,可以让开发者通过创建线程对象来启动线程,而不需要手工创建线程ID。其使用方法如下所示:


#include <iostream>

#include <thread>

using namespace std;

void threadFunc()

{

  for (int i = 0; i < 5; i++)

  

    cout << "Thread Running " << i << endl;

  

}

int main()

{

  thread t1(threadFunc);

  t1.join();

  return 0;

}

上述代码首先定义了一个线程函数threadFunc(),该函数在执行过程中简单地输出一段文字,并在主函数中定义线程对象t1,并以threadFunc()函数作为参数启动该线程,并通过join()方法等待线程执行完毕。运行结果如下:


Thread Running 0

Thread Running 1

Thread Running 2

Thread Running 3

Thread Running 4

2. 使用pthread库

pthread库是一款用于多线程编程的C库,是POSIX线程标准的一部分。其使用方法如下所示:


#include <iostream>

#include <pthread.h>

using namespace std;

void* threadFunc(void*)

{

  for (int i = 0; i < 5; i++)

  

    cout << "Thread Running " << i << endl;

  

  return NULL;

}

int main()

{

  pthread_t threadID;

  pthread_create(&threadID, NULL, threadFunc, NULL);

  pthread_join(threadID, NULL);

  return 0;

}

上述代码中,首先定义了线程函数threadFunc(),其后通过pthread_create()函数创建了一个线程,将线程函数作为参数传入,并使用pthread_join()函数等待线程执行完毕。运行结果如下:


Thread Running 0

Thread Running 1

Thread Running 2

Thread Running 3

Thread Running 4

3. 使用Windows API

如果在Windows操作系统下开发,可以使用Windows API提供的线程库win32创建线程。其使用方法如下所示:


#include <iostream>

#include <Windows.h>

using namespace std;

DWORD WINAPI threadFunc(LPVOID lpParam)

{

  for (int i = 0; i < 5; i++)

  

    cout << "Thread Running " << i << endl;

  

  return 0;

}

int main()

{

  HANDLE hThread;

  DWORD dwThreadID;

  hThread = CreateThread(NULL, 0, threadFunc, NULL, 0, &dwThreadID);

  WaitForSingleObject(hThread, INFINITE);

  CloseHandle(hThread);

  return 0;

}

上述代码中,定义了线程函数threadFunc(),使用CreateThread()函数来创建线程,并使用WaitForSingleObject()函数等待线程执行完毕,最后使用CloseHandle()函数来关闭线程句柄。运行结果如下:


Thread Running 0

Thread Running 1

Thread Running 2

Thread Running 3

Thread Running 4

总结

C++开启多线程的三种方式分别为std::thread、pthread库和Windows API。对于不同的操作系统或硬件平台,选择不同的方式来开启线程可以更加灵活和高效地完成程序开发。开启多线程可以明显地提升程序运行效率和并发处理能力,是C++编程中不可或缺的重要语言特性。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复