Linux 拨号vps windows公众号手机端

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

lewis 1年前 (2024-04-23) 阅读数 15 #程序编程
文章标签 c++

在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类来创建线程,因为它更易用且跨平台性更好。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门