程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 一種簡單易用的C++線程類

一種簡單易用的C++線程類

編輯:C++入門知識

一種簡單易用的C++線程類


一 代碼結構

\

二 代碼

1. threadobject.h

 

/*************************************************************************
    > File Name: threadobject.h
    > Author: wangzhicheng
    > Mail: [email protected] 
    > Created Time: Sat 07 Feb 2015 10:13:33 PM WST
 ************************************************************************/
#ifndef THREADOBJECT_www.Bkjia.com
#define THREADOBJECT_H
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
/*
 *abstract thread class
 * */
class Threadobject {
	private:
		pthread_t mTid;
		string mName;
	protected:
		virtual void do_something(void) = 0;   // the real function which thread need to execute
	public:
		Threadobject();
		~Threadobject();
		void setname(const string &);
		const string& getname() const;
		void run(void);
		void join(void);
		friend void *thread(void *);
};
/*
 * user thread class
 * */
class Userthread:public Threadobject {
	protected:
		virtual void do_something(void);
	public:
		Userthread();
		~Userthread();
};

#endif

 

2. threadobject.cpp

 

/*************************************************************************
    > File Name: threadobject.cpp
    > Author: wangzhicheng
    > Mail: [email protected] 
    > Created Time: Sat 07 Feb 2015 10:32:14 PM WST
 ************************************************************************/
#include "threadobject.h"
void *thread(void *arg);
Threadobject::Threadobject() {
}
Threadobject::~Threadobject() {
}
void Threadobject::run() {
	pthread_create(&this->mTid, NULL, thread, this);
}
void Threadobject::join() {
	pthread_join(this->mTid, NULL);
}
void Threadobject::setname(const string &name) {
	this->mName = name;
}
const string& Threadobject::getname() const {
	return this->mName;
}
void *thread(void *arg) {
	Threadobject *thread = static_cast(arg);
	thread->do_something();

	return NULL;
}
Userthread::Userthread() {
}
Userthread::~Userthread() {
}
void Userthread::do_something(void) {
	cout << this->getname() << endl;
}

3. main.cpp

 

 

/*************************************************************************
    > File Name: main.cpp
    > Author: wangzhicheng
    > Mail: [email protected] 
    > Created Time: Sun 08 Feb 2015 07:53:38 PM WST
 ************************************************************************/
#include "threadobject.h"
int main() {
	Userthread userthread1, userthread2;
	userthread1.setname("userthread1");
	userthread2.setname("userthread2");
	userthread1.run();
	userthread2.run();
	userthread1.join();
	userthread2.join();

	return 0;
}

4. makfile

 

 

CC=g++
all:
	$(CC) -g -o main main.cpp threadobject.cpp threadobject.h -lpthread

三 程序運行截圖

 

\

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved