溫馨提示×

c++創(chuàng)建多線程的方式有哪些

c++
小億
89
2023-11-16 10:32:13
欄目: 編程語言

在C++中,有以下幾種方式可以創(chuàng)建多線程:

  1. 使用 std::thread 類:std::thread 是 C++11 中添加的標(biāo)準(zhǔn)庫類,可以創(chuàng)建一個(gè)新的線程。你可以使用它的構(gòu)造函數(shù)來傳遞一個(gè)可調(diào)用的對象(函數(shù)、函數(shù)指針或者 lambda 表達(dá)式)作為線程的入口點(diǎn)。
#include <iostream>
#include <thread>

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

int main() {
    std::thread t(foo);
    t.join(); // 等待線程結(jié)束
    return 0;
}
  1. 使用 POSIX 線程庫:POSIX 線程庫是一套用于創(chuàng)建和管理線程的標(biāo)準(zhǔn)接口。在 C++ 中,你可以使用 pthread_create 函數(shù)來創(chuàng)建一個(gè)新的線程。
#include <iostream>
#include <pthread.h>

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

int main() {
    pthread_t thread;
    pthread_create(&thread, nullptr, foo, nullptr);
    pthread_join(thread, nullptr); // 等待線程結(jié)束
    return 0;
}
  1. 使用 Windows 線程:在 Windows 系統(tǒng)上,你可以使用 CreateThread 函數(shù)來創(chuàng)建一個(gè)新的線程。
#include <iostream>
#include <windows.h>

DWORD WINAPI foo(LPVOID) {
    std::cout << "Hello from thread!" << std::endl;
    return 0;
}

int main() {
    HANDLE thread = CreateThread(nullptr, 0, foo, nullptr, 0, nullptr);
    WaitForSingleObject(thread, INFINITE); // 等待線程結(jié)束
    CloseHandle(thread);
    return 0;
}

無論使用哪種方式創(chuàng)建線程,都需要注意線程的同步和互斥,以避免數(shù)據(jù)競爭和其他問題。

0