更改属性值时的分段错误

时间:2015-02-02 11:38:39

标签: c++11 raspberry-pi polling

我正在使用C ++ 11类,它将通过I2C获取Raspberry Pi中温度传感器的值。它将轮询值直到它停止。它在单独的线程中进行轮询,因此它不会停止应用程序流。问题是在该文件的第64行:https://github.com/OpenStratos/server/blob/feature/temperature/temperature/Temperature.cpp#L64

void Temperature::read_temperature()
{
    while (this->reading)
    {
        #ifndef OS_TESTING
            int value = wiringPiI2CRead(this->filehandle);
        #else
            int value = 16000;
        #endif

        float voltage = value * 5 / 32768; // 2^15
        float temp = r_to_c(TEMP_R * (TEMP_VIN / voltage - 1));
        this->temperature = temp; // Gives segmentation fault

        this_thread::sleep_for(chrono::milliseconds(50));
    }
}

它给出了分段错误。古老的事情是它并不总是发生。编译完成后,大约75%的时间运行二进制文件会崩溃。

这是委托代码的文件:https://github.com/OpenStratos/server/blob/feature/temperature/testing/temperature_test.cpp

Temperature temp(20);
temp.start_reading();
AssertThat(temp.is_reading(), Equals(true));

// this_thread::sleep_for(chrono::milliseconds(100)); if uncommented less segmentation faults

temp.stop_reading();
AssertThat(temp.is_reading(), Equals(false));

可能会发生什么?如何解决?

1 个答案:

答案 0 :(得分:1)

您需要等待Temperature::read_temperature()退出,因此您需要:

bool reading;
volatile bool stopped;  // volatile required to make the compiler re-read
                        // the value everytime we expect it to.
//
bool is_stopped(){ return stopped; }

void Temperature::start_reading()
{
    if (!reading)
    {
        stopped = false;
        reading = true;
        // etc

void Temperature::read_temperature()
{
    while (this->reading)
    {
    // etc
    }
    stopped=true;
}

temp.stop_reading();
while(!temp.is_stopped();  
AssertThat(temp.is_reading(), Equals(false));
相关问题