读取成员时出现线程段错误

Threading Segfault when reading members

本文关键字:错误 段错误 线程 成员 读取      更新时间:2023-10-16

当我试图在工作线程中读取类变量时,我面临一些问题(该变量未在该线程中创建)。下面是我的类头与静态工作线程函数:

class C1WTempReader
{
public:
    C1WTempReader(std::string device);
    virtual ~C1WTempReader();
    void startTemRead();
    double& getTemperature();
private:
    std::string device;
    std::string path;
    double temperature;
    pthread_t w1Thread;
    std::mutex w1Mutex;

    bool fileExists(const std::string& filename);
    static void * threadHelper(void * arg)
    {
        return ((C1WTempReader*) arg)->tempReadRun(NULL);
    }
    void* tempReadRun(void* arg);
};

以下是我使用的关键方法:

C1WTempReader::C1WTempReader(std::string device)
{
    path = W1_PATH + device + W1_SLAVE;
    if (!fileExists(path))
    {
        std::cout << "File " << path << " doesnt exist!" << std::endl;
        path.clear();
        return;
    }
    std::cout << "1 wire termometer device path: " << path << std::endl;
}
void C1WTempReader::startTempRead()
{
    if(pthread_create(&w1Thread, NULL, threadHelper, NULL) == -1)
    {
        std::cout << "1W thread creation failed" << std::endl;
    }
}
void* C1WTempReader::tempReadRun(void* arg)
{
    w1Mutex.lock(); // SEGFAULT
    std::string line;
    std::ifstream myfile (path.c_str());
    if (myfile.is_open())
    {
            while ( getline (myfile,line) )
            {
                    size_t found = line.find("t=");
                    if (found != std::string::npos)
                    {
                            found += 2;
                            std::string temp = line.substr(found, 10);
                            temperature = atof(temp.c_str());
                            temperature /= 1000;
                            std::cout << "Temperature: " << temperature << " *C" << std::endl;
                    }
                    line.clear();
            }
            myfile.close();
    }
    else
    {
        std::cout << "Unable to open file" << std::endl;
        temperature = 1000; // bad value
    }
    w1Mutex.unlock();
    return NULL;
}
double& C1WTempReader::getTemperature()
{
    if (pthread_join(w1Thread, NULL))
    {
        std::cout << "1W Unable to join thread!" << std::endl;
    }
    return temperature;
}

分段错误发生在tempReadRun方法,只要我试图锁定互斥锁。我没有互斥之前,我注意到,每当我试图读取类创建期间创建的任何类变量,而不是在新线程中创建,它就会发生。我做错了什么?

我是这样运行的:

string device = "28-00000713a636";
C1WTempReader tempReader(device);
tempReader.startTempRead();
.
.
.
double temp = tempReader.getTemperature();

我已经找到问题所在了。在函数C1WTempReader::startTempRead():

if(pthread_create(&w1Thread, NULL, threadHelper, NULL) == -1)
{
     std::cout << "1W thread creation failed" << std::endl;
}

pthread_create的最后一个参数必须更改为:

你没有传递参数给pthread_create:

if(pthread_create(&w1Thread, NULL, threadHelper, this) == -1)