码迷,mamicode.com
首页 > 编程语言 > 详细

C++11 多线程

时间:2020-03-02 20:53:04      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:重点   pre   message   icc   c++11   lock   uniq   als   notify   

做过相关工程很久了,没有记录,发现有些忘记了,又复习了一遍,这里记录下:

我这里的代码做过删减,直接运行不了,重点在于说明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();
void detect_trafficcone(int argc, char** argv);
void get_imginfo(pair<Mat,string>& info);
pair<Mat,string> g_imginfo;
pair<Mat,string> g_imginfoT;
mutex mutex_imginfo;
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);
    sleep(3);
    thread getobjinfo(detect_trafficcone,argc, argv);
    getobjinfo.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); } 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); 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(); } }

 

C++11 多线程

标签:重点   pre   message   icc   c++11   lock   uniq   als   notify   

原文地址:https://www.cnblogs.com/zhibei/p/12397538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!