#include #include #include #include #include #include #define CHANS 2 #define COUNT 10 #define LOOPS 666 struct Mutex{ std::mutex maint2thread, thread2main; }; class Chan { private: std::thread processor; Mutex mut; unsigned char id = 0; static unsigned char chancount; bool stopped = false; public: Chan() { std::thread p(&Chan::play, this); this->processor = std::move(p); mut.maint2thread.lock(); mut.thread2main.lock(); this->id = Chan::chancount++; } void play() { while(true){ this->mut.maint2thread.lock(); if(this->stopped){ break; } //std::cout << "Chan " << +this->id <<" play thread " << std::endl; for(int i = 0; iid <<" finish play thread " << std::endl; this->mut.thread2main.unlock(); } } void wait(){ std::cout << "wait processor " << +this->id << " for finish" << std::endl; this->processor.join(); } void stop(){ std::cout << "stop processor " << +this->id << std::endl; this->stopped = true; this->mut.maint2thread.unlock(); } Mutex* getMut(){ return &this->mut; } }; class Seq_Chan { private: unsigned char id = 0; static unsigned char chancount; public: Seq_Chan() { this->id = Seq_Chan::chancount++; } void play() { //std::cout << "Seq Chan " << +this->id <<" play " << std::endl; for(int i = 0; iid <<" finish play " << std::endl; } }; unsigned char Chan::chancount = 0; unsigned char Seq_Chan::chancount = 0; int main(){ Chan chan[CHANS]; std::chrono::steady_clock::time_point begin0 = std::chrono::steady_clock::now(); for(unsigned int j = 0; j < COUNT; ++j){ //std::cout << "*******************************"<=0; --i){ chan[i].getMut()->maint2thread.unlock(); } for(short i=(CHANS-1); i >=0; --i){ chan[i].getMut()->thread2main.lock(); } //std::cout<<"----add samples-----"<< std::endl; } std::chrono::steady_clock::time_point end0 = std::chrono::steady_clock::now(); for(short i=(CHANS-1); i >=0; --i){ chan[i].stop(); } for(short i=(CHANS-1); i >=0; --i){ chan[i].wait(); } std::cout << "///////////////////////////////////////////////////////////////////////"<=0; --i){ seq_chan[i].play(); } } std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now(); std::cout << "///////////////////////////////////////////////////////////////////////"<(end0 - begin0).count(); double seq_time = std::chrono::duration_cast(end1 - begin1).count(); #define UNIT "µs" std::cout << "THREAD TIME ELAPSED = " << thread_time << UNIT << std::endl; std::cout << "SEQUEN TIME ELAPSED = " << seq_time << UNIT << std::endl; std::chrono::steady_clock::time_point begin_loop = std::chrono::steady_clock::now(); for(int i = 0; i(end_loop - begin_loop).count(); std::cout << "LOOP TIME ELAPSED = " << loop_time << "ns" << std::endl; return 0; }