做过相关工程很久了,没有记录,发现有些忘记了,又复习了一遍,这里记录下:
我这里的代码做过删减,直接运行不了,重点在于说明thread创建框架、锁的使用、条件等待以及双缓冲的使用!
#include <stdio.h> #include <iostream> //thread #include "thread" #include "mutex" #include <condition_variable> struct Content { char img_data[1843200]; }; // Forward function definitions: using namespace cv; using namespace std; bool sendimg = false; void get_img();//线程1函数 void detect_trafficcone(int argc, char** argv); //线程2函数 void get_imginfo(pair<Mat,string>& info); pair<Mat,string> g_imginfo;//缓存1 pair<Mat,string> g_imginfoT;//缓存2 mutex mutex_imginfo;//mutex锁 condition_variable cond_imginfo;//条件变量 bool g_imginfo_flag = false;//信号量 string g_send_img = "name=detector5;timestamp="; bool g_send_flag = false; mutex mutex_send_img; condition_variable cond_send_img; int main(int argc, char** argv) { thread getframe(get_img);//起线程1 sleep(3); thread getobjinfo(detect_trafficcone,argc, argv);//起线程2 getobjinfo.join();//.join是等待式结束,上面运行完毕才结束线程 getframe.join(); return 0; } void get_imginfo(pair<Mat,string>& info) {
//双缓冲交换数据 g_imginfoT = info; info = g_imginfo; g_imginfo = g_imginfoT; } void detect_trafficcone(int argc, char** argv) { while(true) { pair<Mat,string> imginfo; unique_lock<mutex> lock_imginfo(mutex_imginfo); while(!g_imginfo_flag) { cond_imginfo.wait(lock_imginfo);//等待cond_imginfo条件提醒,接收到提醒後先上锁,然后检查个g_imginfo_flag是否满足条件,满足就向下进行,不满足解锁。 } get_imginfo(imginfo); g_imginfo_flag = false; lock_imginfo.unlock(); Mat recv_img = imginfo.first; string timestamp = imginfo.second; cout<<"detect trafficcone ..."<<endl; imshow("recv_img",recv_img); waitKey(0); send_img = send_img + "trafficcone_num="+to_string(box_num)+posboxs; unique_lock<mutex> lock_send_img(mutex_send_img);//unique_lock互斥锁,管理mutex的工具,此时对mutex_send_img加锁 g_send_img = send_img; g_send_flag = true; lock_send_img.unlock();//解锁,省略不写的话,该函数运行结束自动解锁 cond_send_img.notify_all();//条件提醒 cout<<"send_img:"<<send_img<<endl; } } void get_img() { while(true) { unique_lock<mutex> lock_imginfo(mutex_imginfo); g_imginfo.first = recv_img; g_imginfo.second = timestamp; g_imginfo_flag = true; lock_imginfo.unlock(); cond_imginfo.notify_all(); unique_lock<mutex> lock_send_img(mutex_send_img); while(!g_send_flag) { cond_send_img.wait(lock_send_img); } zmq::message_t req_message(strlen(g_send_img.c_str())); memcpy((void*)req_message.data(),g_send_img.c_str(), strlen(g_send_img.c_str())); REQsocket.send(req_message); g_send_flag = false; lock_send_img.unlock(); } }