Linux下C编程2--线程的练习

先挖坑,周末再补==

对于多线程的demo,主要在尝试封装 thread类来简化创建多线程的步骤:

主要参考文章:跳转1

线程基类  BaseThread:主要提供接口

自己的功能线程类  MyThread: 主要去实现你的线程中希望执行的操作

#ifndef CTHREAD_HH
#define CTHREAD_HH

#include <stdio.h>
#include <iostream>
#include <pthread.h>
class BaseThread
{
public:
	
	BaseThread();
	virtual ~BaseThread();

	//开始创建线程并执行
	bool start();

	//阻塞直到等待线程退出
	bool wait();	

	//线程入口函数,用静态全局
	static void* ThreadEntranc(void* args);
	
	//线程的真正要执行任务放在这里。ThreadEntranc中调用这个函数
	virtual void Run()=0;
	

private:
	
	pthread_t m_threadID;

};


class MyThread:public BaseThread
{
public:

	//继承之后只需要重写这个线程内部执行动作函数	
	virtual void Run();
	
};


#endif

  

来看对应的实现

#include "CThread.h"

BaseThread::BaseThread()
{

}

BaseThread::~BaseThread()
{
	printf("~BaseThread()\n");
}

bool BaseThread::start()
{
	int iRet = -1;
	iRet = pthread_create(&m_threadID, NULL, ThreadEntranc, this);
	if(0 != iRet)
	{
		printf("pthread_create error,iRet: %d\n",iRet);
		return false;
	}
	return true;		
}

bool BaseThread::wait()
{
	int iRet = -1;
	iRet = 	pthread_join(m_threadID,NULL);
	if(0 != iRet)
	{
		printf("pthread_join error,iRet: %d\n",iRet);
		return false;
	}
	printf("pthread_join over\n");
	return true;	
}

void* BaseThread::ThreadEntranc(void* args)
{
	BaseThread* p = NULL;
	p = static_cast<BaseThread*>(args);
	if(NULL != p)
	{
		p->Run();
	}
	else
	{
		printf("获取线程实例指针失败\n");
	}
	return NULL;
}



void MyThread::Run()
{
	for(int i=0; i<5; i++)
	{
		printf("--- this mythred--\n");
	}
	return ;
}

  

主程序中的调用

#include "CThread.h"

int main()
{
	MyThread test;
	test.start();
	test.wait();
	return 0;
}

  

posted @ 2018-07-11 22:51  耳边呢喃  阅读(205)  评论(0编辑  收藏  举报