所以我有一个 Kinect 程序,它具有三个主要功能,即收集数据和保存数据。我希望其中一个函数尽可能多地执行,而其他两个函数每秒可能运行 10 次。
while(1)
{
...
//multi-threading to make sure color and depth events are aligned -> get skeletal data
if (WaitForSingleObject(colorEvent, 0) == 0 && WaitForSingleObject(depthEvent, 0) == 0)
{
std::thread first(getColorImage, std::ref(colorEvent), std::ref(colorStreamHandle), std::ref(colorImage));
std::thread second(getDepthImage, std::ref(depthEvent), std::ref(depthStreamHandle), std::ref(depthImage));
if (WaitForSingleObject(skeletonEvent, INFINITE) == 0)
{
first.join();
second.join();
std::thread third(getSkeletonImage, std::ref(skeletonEvent), std::ref(skeletonImage), std::ref(colorImage), std::ref(depthImage), std::ref(myfile));
third.join();
}
//if (check == 1)
//check = 2;
}
}
目前我的线程让它们都在同一时间运行,但这会大大降低我的计算机速度,我只需要运行“getColorImage”和“getDepthImage”可能是 5-10 次/秒,而“getSkeletonImage”我想尽可能多地运行。
我希望“getSkeletonImage”以最大频率运行(通过 while 循环约 30 次/秒)然后“getColorImage”和“getDepthImage”进行时间同步(通过 while 循环约 5-10 次/秒)
有什么方法可以做到这一点?我已经在使用线程,但我需要一个线程持续运行,然后另外两个基本上间歇性地加入。感谢您的帮助。
最佳答案
目前,您的主循环在每次迭代时创建线程,这表明每个线程函数运行一次直至完成。这引入了每次创建和销毁线程的开销。
就个人而言,我根本不会为线程而烦恼。相反,在主线程中我会做
void RunSkeletonEvent(int n)
{
for (i = 0; i < n; ++i)
{
// wait required time (i.e. to next multiple of 1/30 second)
skeletonEvent();
}
}
// and, in your main function ....
while (termination_condition_not_met)
{
runSkeletonEvent(3);
colorEvent();
runSkeletonEvent(3);
depthEvent();
}
这会交错事件,因此每次运行 depthEvent()
和 colorEvent()
时,skeletonEvent()
运行六次。只需根据需要调整数字以获得所需的行为。
您需要为所有事件设计代码,使它们不会超时运行(如果超时,所有后续事件都将延迟 - 没有办法阻止)。
接下来您需要解决的问题是如何等待触发骨架事件的时间。检索时钟时间、计算等待时间并在该间隔内休眠的过程将完成。通过休眠(线程产生其时间片),您的程序也会变得更好一些(例如,它不会让其他进程占用处理器时间)。
一个优点是,如果要在“事件”之间共享数据(例如,所有事件都修改了一些全局数据),则不需要同步,因为上面的循环保证只有一个“事件”访问共享一次数据。
注意:您对 WaitForSingleObject()
的使用表明您正在使用 Windows。 Windows(除此之外,在弱意义上可以说是 CE)并不是真正的实时系统,因此不能保证精确的计时。换句话说,您达到的实际间隔会有所不同。
重组使用线程仍然是可能的。从你的描述来看,没有证据表明你真的需要这样的东西,所以我就此回复。
关于c++ - 基于时间间隔执行函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30006697/