• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++之MutexLock和MutexLockGuard封装

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

noncopyable.h

 

#ifndef __WD_NONCOPYABLE_H__
#define __WD_NONCOPYABLE_H__


namespace wd
{

class Noncopyable
{
protected:
	Noncopyable(){}
	~Noncopyable(){}
private:
	Noncopyable(const Noncopyable&);
	Noncopyable & operator=(const Noncopyable &);
};

}//end of namespace wd

#endif

thread.h

#ifndef __WD_MUTEXLOCK_H__
#define __WD_MUTEXLOCK_H__

#include "Noncopyable.h" #include <pthread.h> namespace wd { class MutexLock
:public Noncopyable //表达语义 { public: MutexLock() { pthread_mutex_init(&_mutex, NULL); } ~MutexLock() { pthread_mutex_destroy(&_mutex); } void lock() { pthread_mutex_lock(&_mutex);} void unlock() { pthread_mutex_unlock(&_mutex);} pthread_mutex_t * getMutexLockPtr() { return &_mutex; } private: pthread_mutex_t _mutex; }; //RAII class MutexLockGuard { public: MutexLockGuard(MutexLock & mutex) : _mutex(mutex) { _mutex.lock(); } ~MutexLockGuard() { _mutex.unlock(); } private: MutexLock & _mutex; }; }//end of namespace wd #endif

  

thread.cc

#include "Thread.h"
#include <iostream>

using std::cout;
using std::endl;
using namespace wd; 


Thread::Thread()
: _pthid(0)
, _isRunning(false)
{}


void Thread::start()
{
	pthread_create(&_pthid, NULL, threadFunc, this);
	_isRunning = true;
}

void * Thread::threadFunc(void * arg)
{
	Thread * pthread = static_cast<Thread*>(arg);
	if(pthread)
		pthread->run();// 执行任务

	return NULL;
}

void Thread::join()
{
	pthread_join(_pthid, NULL);
	_isRunning = false;
}

Thread::~Thread()
{
	if(_isRunning)	
	{
		pthread_detach(_pthid);// 将运行的线程交给系统进行托管
		_isRunning = false;
	}
}

  

testThread.cc

#include "Thread.h"

#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;

class MyThread
: public wd::Thread
{
	void run()
	{
		::srand(::time(NULL));
		int cnt = 10;
		while(cnt--) {
			int number = ::rand() % 100;
			cout << ">> Thread "<< pthread_self() << " get a number : " << number << endl;
			::sleep(1);
		}
	}
};
 
int main(void)
{
	cout << "MainThread: " << pthread_self() << endl;
	unique_ptr<wd::Thread> myThread(new MyThread());//线程对象在主线程
	myThread->start();
	myThread->join();

	return 0;
}

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
解决cv2.error:OpenCV(4.1.1)C:\projects\opencv-python\opencv\modules\imgproc\src\ ...发布时间:2022-07-18
下一篇:
C#NotifyIcon托盘控件发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap