在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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__
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; }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论