【发布时间】:2014-07-10 19:05:48
【问题描述】:
(我讨厌写这样的标题。但我找不到更好的东西)
我有两个有两个线程的类。第一个检测两帧之间的运动:
void Detector::run(){
isActive = true;
// will run forever
while (isActive){
//code to detect motion for every frame
//.........................................
if(isThereMotion)
{
if(number_of_sequence>0){
theRecorder.setRecording(true);
theRecorder.setup();
// cout << " motion was detected" << endl;
}
number_of_sequence++;
}
else
{
number_of_sequence = 0;
theRecorder.setRecording(false);
// cout << " there was no motion" << endl;
cvWaitKey (DELAY);
}
}
}
第二个将在开始时录制视频:
void Recorder::setup(){
if (!hasStarted){
this->start();
}
}
void Recorder::run(){
theVideoWriter.open(filename, CV_FOURCC('X','V','I','D'), 20, Size(1980,1080), true);
if (recording){
while(recording){
//++++++++++++++++++++++++++++++++++++++++++++++++
cout << recording << endl;
hasStarted=true;
webcamRecorder.read(matRecorder); // read a new frame from video
theVideoWriter.write(matRecorder); //writer the frame into the file
}
}
else{
hasStarted=false;
cout << "no recording??" << endl;
changeFilemamePlusOne();
}
hasStarted=false;
cout << "finished recording" << endl;
theVideoWriter.release();
}
布尔记录被函数改变:
void Recorder::setRecording(bool x){
recording = x;
}
目标是在检测到运动后开始录制,同时防止程序开始录制两次。
真正奇怪的问题,老实说在我的脑海中没有任何意义,代码只有在我计算布尔记录(标有“++++++”)时才能工作。 Else 记录永远不会更改为 false,并且 else 语句中的代码永远不会被调用。
有没有人知道为什么会发生这种情况。我还只是从 c++ 开始,但这个问题对我来说似乎很奇怪..
【问题讨论】:
-
你尝试
std::atomic<bool>输入isActive和recording变量了吗? -
这绝对是一个竞争条件。 cout 引入了足够的延迟来更改执行顺序。
-
在有人提出
volatile之前:不! -
@isADon 因为如果你不将变量声明为
atomic编译器可以假设没有其他线程会更改字段的值并将其缓存(这是一个很好且简单的解释和细节上完全错误,但这是一个好的开始)。 -
@isADon 您可以只使用QMutex 或QT 提供的任何其他同步机制。 (不幸的是,这会将每次读取都变成共享数据的写入——互斥体本身——这会稍微影响性能,但通常没关系。)
标签: c++ multithreading boolean