I am a newbie in std::thread and std::condition_variable.
I would like to use 2 threads: one for display (void showCalibration()) and the other for processing (void CaptureFrame()). These threads access a global variable (temp_pupil).
The display thread will clear the variable after a specific time to get the data (pupil) from processing thread (during that time).
I used loops to "simulate" capture loop from a high speed camera (void CaptureFrame()) and 9 calibration points displayed on the screen (void showCalibration()
#include <opencv2/core/core.hpp>
#include <iostream>
#include <thread>
#include <mutex>
std::vector<cv::Point2d> temp_pupil;
std::mutex mu;
std::condition_variable cond;
void showCalibration()
{
for (int i = 0; i <= 9; i++)//plot 9 points sequentially
{
std::unique_lock<std::mutex> lk(mu);
{
temp_pupil.clear();//prepare for get new data
}
lk.unlock();
cond.notify_one();//signal CaptureFrame() to capture data
std::this_thread::sleep_for(std::chrono::milliseconds(100));//specific time
lk.lock();
{
while (temp_pupil.empty())
{
cond.wait(lk);//wait CaptureFrame() to end current point
}
std::string cal = std::to_string(temp_pupil.size()) + "Cali" + std::to_string(i) + "n";
std::cout << cal;//print
}
lk.unlock();
}
}
void CaptureFrame()
{
cv::Point2d pupil;
for (int i = 0; i <= 500; i++)
{
std::unique_lock<std::mutex> lk(mu);
{
pupil = cv::Point2d(i, i);//create data
temp_pupil.push_back(pupil);//get data
std::string cap = std::to_string(temp_pupil.size()) + "Captue" + std::to_string(i) + "n";
std::cout << cap;//print
}
lk.unlock();
cond.notify_one();//signal showCalibration() to end current point
}
}
int main()
{
std::thread cal_thread(showCalibration);//display thread
std::thread cap_thread(CaptureFrame);//process thread
cal_thread.join();
cap_thread.join();
}
Could anyone help me review above code ?