zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++11之thread智能指针(一百零八)

C++智能 11 指针 thread
2023-09-14 09:09:57 时间

1.代码示例  

//1.class_demo.h
#include <iostream>
#include <thread>
#include <chrono>
#include <unistd.h>
using namespace std;

class Audio{
public:
	bool loop_back_ = 1;
	Audio(int n);
	~Audio();
	std::thread* thread_id_;
	//void process();
};






//2.class_demo.cpp
#include "class_demo.h"

void process(void *data){
	auto thiz = static_cast<Audio*>(data);
	while(thiz->loop_back_){	
		this_thread::sleep_for(chrono::seconds(1));
		printf("xxx-------->%s(), line = %d, loop_back = %d\n",__FUNCTION__,__LINE__,thiz->loop_back_);
	}	
}

Audio::Audio(int n){
	thread_id_ = new thread(process, this);
	printf("xxx-------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}

Audio::~Audio(){
	this->loop_back_ = 0;
	printf("xxx-------->%s(), line = %d, loop_back = %d\n",__FUNCTION__,__LINE__,this->loop_back_);
}

int main(){
	//way 1:
	//Audio *audio = new Audio();

	//way 2:
	shared_ptr<Audio> audio = make_shared<Audio>(3);

	//1.join(); thread sync
	//audio->thread_id_->join();

	//2.datech(); thread async
	audio->thread_id_->detach();
	sleep(1);
	printf("xxx-------->%s(), line = %d\n",__FUNCTION__,__LINE__);
	
	//delete audio;
}