Foo.h
#pragma once
#include <stdint.h>
#include <cstddef>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <atomic>
class Foo: public FooAncestor
{
private:
std::atomic_bool start = false;
//I do a shared mutex on the currentvalue,//but I took it out in order to make sure that it was not part of the problem
mutable std::shared_mutex valueMutex;
float currentvalue = 0.0;
public:
Foo();
void Start();
inline float Getvalue() { return currentvalue; }
};
Foo.cpp
#include "Foo.h"
using namespace std::chrono_literals;
Foo::Foo()
{
//setting up things not related to the subject
}
void Foo::Start()
{
std::thread updateThread( [=]()
{
start = true;
while( start )
{
//a whole bunch of commented out code which doesn't make any difference to this
std::this_thread::sleep_for( 200ms );
currentTemp += 1;
}
} );
updateThread.detach();
}
Main.cpp
int main()
{
std::cout << "hello from PiCBake!\n";
int i = 0;
//a bunch of additional setup code here,not related to this class
Foo foo = Foo();
foo.Start();
for( ;;)
{
//this part is just for testing of the class and has no actual function
std::cout << max.GetTemp() << std::endl;
delay( 500 );
if( ++i == 10 )
i = 0;
}
return 0;
}
每当我包含此内容,或者在updateThread部分的开头进行单独测试时(例如:if(!run)return;),代码流都会产生奇怪的结果。在调试中,它一直跳到要测试“运行”的部分,甚至在线程中设置运行时跳出while循环,但是在创建线程之前设置运行时,行为是相同的。
如果线程很长,则实际上根本无法完成。每当我删除变量'run'并将其替换为“ true”时,所有工作都会按预期进行。如果我将“ while(run)”替换为“ while(true)”,但是在if语句之后立即测试“ run”,则会发生相同的情况。 尝试使运行原子化,尝试了一堆其他事情,删除所有内容等。
请注意,我尚未实现线程退出条件。可以在析构函数或其他东西中将“ run”设置为false以便退出线程。但这不是真正的问题。
更新:
肯定已经晚了,我可能正在转圈。似乎将起始值更改为atomic已经解决了,无论哪种方式,它都可以工作,而且我不知道^&*()出了什么问题……