• 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()
    ");
    }
    
    bool BaseThread::start()
    {
    	int iRet = -1;
    	iRet = pthread_create(&m_threadID, NULL, ThreadEntranc, this);
    	if(0 != iRet)
    	{
    		printf("pthread_create error,iRet: %d
    ",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
    ",iRet);
    		return false;
    	}
    	printf("pthread_join over
    ");
    	return true;	
    }
    
    void* BaseThread::ThreadEntranc(void* args)
    {
    	BaseThread* p = NULL;
    	p = static_cast<BaseThread*>(args);
    	if(NULL != p)
    	{
    		p->Run();
    	}
    	else
    	{
    		printf("获取线程实例指针失败
    ");
    	}
    	return NULL;
    }
    
    
    
    void MyThread::Run()
    {
    	for(int i=0; i<5; i++)
    	{
    		printf("--- this mythred--
    ");
    	}
    	return ;
    }
    

      

    主程序中的调用

    #include "CThread.h"
    
    int main()
    {
    	MyThread test;
    	test.start();
    	test.wait();
    	return 0;
    }
    

      

  • 相关阅读:
    Unity3D_08_XML文件创建,读取,修改,添加
    Unity3D_07_日志、文本打印
    Unity3D_06_根据Transform、GameObject和Tag获取子对象集合
    Unity3D_05_理解Unity的新GUI系统(UGUI)
    Unity3D_04_GameObject,Component,Time,Input,Physics
    Unity3D_03_代码及效率优化总结
    Unity3D_02_基类MonoBehaviour/自带函数以及脚本执行的生命周期
    Unity3D_01_各种寻找GameObject方法
    人工智能相关
    ubuntu 安装 typora
  • 原文地址:https://www.cnblogs.com/iamcdx-2017/p/9297131.html
Copyright © 2020-2023  润新知