温馨提示×

c++ pthread库怎么调用

小亿
101
2023-10-25 19:27:32
栏目: 编程语言

要使用pthread库,需要引入头文件#include <pthread.h>

下面是一个简单的示例,展示了如何使用pthread库创建和运行一个线程。

#include <iostream>
#include <pthread.h>

// 线程函数,用于并行执行的任务
void* threadFunction(void* arg) {
    std::cout << "Hello from thread!" << std::endl;
    return nullptr;
}

int main() {
    pthread_t threadId;  // 存储线程ID的变量

    // 创建线程,传入线程函数和参数
    int result = pthread_create(&threadId, nullptr, threadFunction, nullptr);
    if (result != 0) {
        std::cerr << "Failed to create thread." << std::endl;
        return 1;
    }

    // 等待线程结束
    result = pthread_join(threadId, nullptr);
    if (result != 0) {
        std::cerr << "Failed to join thread." << std::endl;
        return 1;
    }

    std::cout << "Thread completed." << std::endl;
    return 0;
}

在这个示例中,pthread_create()函数用于创建一个新线程,并将线程ID存储在threadId变量中。该函数的参数包括线程ID变量、线程属性(可设置为nullptr,使用默认属性)、线程函数和函数参数。

创建线程后,可以使用pthread_join()函数等待线程完成。pthread_join()函数将阻塞主线程,直到指定的线程执行完毕。

注意:需要使用编译器支持C++11或更高版本的标准,以及支持pthread库的操作系统或编译环境。

0