zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    [ZJOI2008]树的统计 树链剖分
    CF915E 动态开线段树
    Poj 2114 Boatherds(点分治)
    Poj 2599 Godfather(树的重心)
    Bzoj 2152: 聪聪可可(点分治)
    Cogs 1714. [POJ1741][男人八题]树上的点对(点分治)
    Cogs 329. K- 联赛(最大流)
    Cogs 731. [网络流24题] 最长递增子序列(最大流)
    Bzoj 2282: [Sdoi2011]消防(二分答案)
    Cogs 732. [网络流24题] 试题库(二分图)
  • 原文地址:https://www.cnblogs.com/iamcdx-2017/p/9297131.html
Copyright © 2011-2022 走看看