更改属性值时出现分段错误

Segmentation fault when changing value of attribute

我正在使用 C++11 class 工作,它将通过 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));

会发生什么?如何修复?

您需要等待 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));