1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include<iostream> #include<thread> #include<fstream> #include< sstream> //stringstream
using namespace std;
class A { public: A() { m_fid.open("out.txt"); m_last_num = 0; m_num = 0; }; ~A() { m_fid.close(); }
void getSequence(int in[],int index,bool &out) { std::stringstream ss; ss << std::this_thread::get_id(); unsigned int id = std::stoull(ss.str()); srand(id);
out = false; int randnum = rand() % 3; printf("%d\n",randnum); out = randnum; if ((out==0)&&(m_num-m_last_num>=50)) { out = true; m_last_num = m_num; } else { out = false; } }
void recog3D(int in[]) { m_num++; bool isGet[4] = {false}; thread t1(&A::getSequence, this, in, 0, std::ref(isGet[0])); // 线程不能为同一个this对象,否则里面成员变量资源争夺,加互斥锁可以解决;此示例中成员变量资源共享,4个线程函数只要任何一个有发生(isGet某一个为true时)每次发生间隔保证至少50帧以上! thread t2(&A::getSequence, this, in, 1, std::ref(isGet[1])); thread t3(&A::getSequence, this, in, 2, std::ref(isGet[2])); thread t4(&A::getSequence, this, in, 3, std::ref(isGet[3])); t1.join(); t2.join(); t3.join(); t4.join(); m_fid << "numframe:" << m_num << ",isGet:a" << isGet[0] << ",b" << isGet[1] << ",c" << isGet[2] << ",d" << isGet[3] << endl; }
private: ofstream m_fid; int m_last_num; int m_num; };
void main() { A a; int in[4] = { 1,2,3,4 };
for (size_t i = 0; i < 2000; i++) { a.recog3D(in); }
}
|