一种简单易用的C++线程类

一 代码结构

二 代码

1. threadobject.h

/*************************************************************************
    > File Name: threadobject.h
    > Author: wangzhicheng
    > Mail: 2363702560@qq.com 
    > Created Time: Sat 07 Feb 2015 10:13:33 PM WST
 ************************************************************************/
#ifndef THREADOBJECT_H
#define THREADOBJECT_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <string>
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: 2363702560@qq.com 
    > 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<Threadobject *>(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: 2363702560@qq.com 
    > 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

三 程序运行截图


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值