如何在 class 构造函数中初始化 pthread_t 变量

How to initialized pthread_t variable in class constructor

如何在 class 构造函数中初始化 pthread_t 变量。

C++ 静态分析(覆盖率)错误:非静态 class 成员 threadId 未在此构造函数中或它调用的任何函数中初始化。

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

#include <unistd.h>

void * 
threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    return NULL;
}

class threads
{
    private:
        pthread_t threadId;
        int err;
    public:
        threads():err(0){};
        ~threads(){};
        void create_thread();
        void join_thread();
};

void
threads::create_thread()
{
  // Create a thread that will function threadFunc()
    err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
    }
    else
    {
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    }

}

void
threads::join_thread()
{
   err = pthread_join(threadId, NULL);
    // check if joining is sucessful
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
    }
}


int main()
{
    threads T;
    T.create_thread();
    T.join_thread();    
    std::cout << "Exiting Main" << std::endl;
    return 0;
}

注:

我已经尝试过这个并且它有效(发布答案,以帮助他人)

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

#include <unistd.h>

void * 
threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    return NULL;
}

class threads
{
    private:
        pthread_t threadId;
        int err;
    public:
        threads():err(0){ threadId = pthread_t(); std::cout <<threadId<<std::endl;};
        ~threads(){};
        void create_thread();
        void join_thread();
};

void
threads::create_thread()
{
  // Create a thread that will function threadFunc()
    err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
    }
    else
    {
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    }

}

void
threads::join_thread()
{
   err = pthread_join(threadId, NULL);
    // check if joining is sucessful
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
    }
}


int main()
{
    threads T;
    T.create_thread();
    T.join_thread();    
    std::cout << "Exiting Main" << std::endl;
    return 0;
}