你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux下的线程类封装

[日期:2009-12-11] 来源:blog.csdn.net/fo1_sky  作者:fo1_sky [字体:大 中 小]

下面的代码是如何使用:testthread.cpp

view plaincopy to clipboardprint?
#include <stdio.h>  
#include <iostream>  
#include <pthread.h>  
#include <sys/time.h>  
#include <string>  
#include "blmutex.h"  
#include "basethread.h"  
using namespace std;  
BL_Mutex am;  
void *thread1 (void* data )  
{  
  for ( int i = 0; i < 10; i ++ )  
  {  
    BL_Lock bl ( &am );  
    usleep(1000);  
    cout << "in thread" << endl;  
  }  
  return (void*)0;  
};  
class CMyThread : public CBaseThread  
{  
  public:  
    virtual bool Init() { return true; };  
    virtual void Runonce()  
    {  
      {  
        cout << "In CMyThread" << endl;  
        usleep(100);  
      }  
    };  
    virtual void Clear() {};  
};  
int main ( int argc, char *argv [] )  
{  
  string str;  
  str = "hello world";  
  cout << str << endl;  
  pthread_t t;  
  pthread_create ( &t, NULL, thread1, NULL );  
  CMyThread mythread;  
  mythread.start("MyThread");  
  for ( int i = 10; i < 20; i ++ )  
  {  
    BL_Lock bl ( &am );  
    usleep(400);  
    cout << "in main " << endl;  
  }  
  pthread_join ( t, NULL );  
  mythread.end();  
  cout << "exit" << endl;  
  return 0;  
} 
#include <stdio.h>
#include <iostream>
#include <pthread.h>
#include <sys/time.h>
#include <string>
#include "blmutex.h"
#include "basethread.h"
using namespace std;
BL_Mutex am;
void *thread1 (void* data )
{
  for ( int i = 0; i < 10; i ++ )
  {
    BL_Lock bl ( &am );
    usleep(1000);
    cout << "in thread" << endl;
  }
  return (void*)0;
};
class CMyThread : public CBaseThread
{
  public:
    virtual bool Init() { return true; };
    virtual void Runonce()
    {
      {
        cout << "In CMyThread" << endl;
        usleep(100);
      }
    };
    virtual void Clear() {};
};
int main ( int argc, char *argv [] )
{
  string str;
  str = "hello world";
  cout << str << endl;
  pthread_t t;
  pthread_create ( &t, NULL, thread1, NULL );
  CMyThread mythread;
  mythread.start("MyThread");
  for ( int i = 10; i < 20; i ++ )
  {
    BL_Lock bl ( &am );
    usleep(400);
    cout << "in main " << endl;
  }
  pthread_join ( t, NULL );
  mythread.end();
  cout << "exit" << endl;
  return 0;
}

就像testthread.cpp中的一样,从CBaseThread继承来的一个CMyThread,重写了Init,Runonce,Clear三个函数,就可以用了。线程的属性是用的默认属性,其它属性设置还没有完成,不过,这个类现在可以用了。

linux
相关资讯       Linux编程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款