读取成员时出现线程段错误
Threading Segfault when reading members
当我试图在工作线程中读取类变量时,我面临一些问题(该变量未在该线程中创建)。下面是我的类头与静态工作线程函数:
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)
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?