pthread_create函数

发布于:2025-02-10 ⋅ 阅读:(39) ⋅ 点赞:(0)

函数原型

pthread_create 是 POSIX 线程(pthread)库中的一个函数,用于在程序中创建一个新线程。

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                void *(*start_routine) (void *), void *arg);

参数解释

  1. pthread_t *thread: 这是一个指向 pthread_t 类型的指针,用于存储新创建线程的线程标识符。调用者必须分配这个指针,pthread_create 会将其设置为新线程的标识符。
  2. const pthread_attr_t *attr: 这是一个指向 pthread_attr_t 结构的指针,用于指定线程的属性。如果设置为 NULL,则使用默认属性。常见的属性包括线程的调度策略、优先级、堆栈大小等。
  3. void *(*start_routine) (void *): 这是一个指向线程函数的指针。这个函数是新线程启动后要执行的函数。它的返回类型是 void*,并接受一个 void* 类型的参数。
  4. void *arg: 这是传递给线程函数的参数。该参数的类型是 void*,因此可以传递任何类型的数据,只需在线程函数中进行适当的类型转换。

返回值

  • 成功时,pthread_create 返回 0
  • 失败时,返回一个非零的错误码。

代码示例 

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <thread>   //包含C++标准线程头文件
#include <sstream>  //包含字符串流头文件

void inputCurPthreadId()
{
    //通过C++标准库获取当前线程号
    std::thread::id threadID = std::this_thread::get_id();
    //将 std::thread::id 转换为一种 QDebug 能够处理的类型
    std::ostringstream oss;
    oss << threadID;
    std::string threadIDStr = oss.str();
    qDebug() << "[C++] This Thread Id = " << QString::fromStdString(threadIDStr);

    //Qt QThread类获取当前线程
    qDebug() << "[Qt] This Thread = " << QThread::currentThread() << "\n";
}

// 线程函数
void* threadFunction(void* arg) 
{
    qDebug() << "In pthread_create:";
    inputCurPthreadId();
    int threadNumber = *((int*)arg);
    std::cout << "Hello from thread " << threadNumber << "!\n";
    sleep(2); // 模拟一些工作
    std::cout << "Thread " << threadNumber << " is exiting.\n";
    pthread_exit(NULL); // 退出线程
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "before pthread_create:";
    inputCurPthreadId();

    pthread_t thread;
    int threadNumber = 1;

    // 创建线程
    if (pthread_create(&thread, NULL, threadFunction, (void*)&threadNumber) != 0) {
        std::cerr << "Error creating thread\n";
        return 1;
    }

    // 等待线程完成
    if (pthread_join(thread, NULL) != 0) {
        std::cerr << "Error joining thread\n";
        return 2;
    }

    qDebug() << "after pthread_create:";
    inputCurPthreadId();

    std::cout << "Main thread is exiting.\n";
    
    return a.exec();
}

注意事项

  1. 线程同步:多个线程可能会访问共享资源,因此需要使用同步机制(如互斥锁、条件变量等)来避免竞争条件。
  2. 线程属性:如果需要设置特定的线程属性(如堆栈大小、调度策略等),可以使用 pthread_attr_set* 函数族来配置 pthread_attr_t 结构。
  3. 线程退出:线程可以通过调用 pthread_exit 函数来退出,或者在线程函数中返回。主线程在所有其他线程完成之前不应该退出,否则会导致程序异常终止。
  4. 线程清理:使用 pthread_join 函数等待线程完成并回收其资源。如果不需要等待线程完成,可以使用 pthread_detach 函数将线程分离。

网站公告

今日签到

点亮在社区的每一天
去签到