c++中创建线程的方法是什么

c++
691
2024/6/4 10:30:09
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中创建线程的方法通常有两种:使用std::thread类或者使用POSIX线程库。

  1. 使用std::thread类:
#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread myThread(threadFunction);
    myThread.join(); //等待线程执行完毕
    return 0;
}
  1. 使用POSIX线程库:
#include <iostream>
#include <pthread.h>

void* threadFunction(void* arg) {
    std::cout << "Hello from thread!" << std::endl;
    return nullptr;
}

int main() {
    pthread_t thread;
    pthread_create(&thread, nullptr, threadFunction, nullptr);
    pthread_join(thread, nullptr); //等待线程执行完毕
    return 0;
}

需要注意的是,在C++11标准之后,推荐使用std::thread类来创建线程,因为它更易用且跨平台性更好。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++常量引用的方法是什么