在阅读成员时线程化Segfault

时间:2015-06-08 13:08:30

标签: c++ multithreading class

当我尝试在我的工作线程中读取一个类变量时,我遇到了一些问题(该变量不是用该线程创建的)。这是我的带有静态工作线程函数的类头:

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();

2 个答案:

答案 0 :(得分:2)

我发现了问题所在。在函数C1WTempReader :: startTempRead()中:

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

pthread_create的最后一个参数必须改为this。

答案 1 :(得分:0)

您没有将参数传递给pthread_create:

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