Linux多线程系列-1-线程使用

来源:互联网 发布:c语言数据结构与算法 编辑:程序博客网 时间:2024/06/04 23:27

linux下常用线程库为POSIX线程(pthread),可运行于Solaris、FreeBSD、Linux 等平台,Windows平台亦有pthread-win32可供使用。

常用类型:

#include <pthread.h>pthread_t pthread_attr_t
pthread_t代表线程ID,不同平台是不同的数据类型,如Linux 2.4.22用无符号长整型表示pthread_t,Solaris 9 用无符号整数,FreeBSD5.2和Mac OS X 10.3用指向pthread结构的指针。pthread_attr_t, 线程属性。

常用函数:

int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void), void *restrict arg);
新建线程:线程从start_rtn函数开始运行,该函数只有一个无类型指针参数arg。

void pthread_exit(void *rval_ptr)
终止线程:线程通过调用pthread_exit停止执行。

int pthread_join(pthread_t thread, void **rval_ptr)
等待线程:调用者调用该函数,以阻塞的方式等待线程thread结束。用于等待thread结束,回收其资源;如果不调用,线程结束运行后会成为僵尸线程,资源得不到释放。

int pthread_detach(pthread_t tid)
分离线程:使线程tid进入分离状态,tid运行结束后会自动释放所有资源。如果不想阻塞主线程,又使其正确运行和结束后释放资源,就可以使用该函数。

如下是项目中,对pthread的封装,便于使用。

Thread.h

#include <pthread.h>class Thread{public:  static const int THREAD_STATUS_NEW = 0; //线程的状态-新建  static const int THREAD_STATUS_RUNNING = 1; //线程的状态-正在运行  static const int THREAD_STATUS_EXIT = -1; //线程的状态-运行结束  Thread();  virtual ~Thread();  virtual void run() = 0; //线程的运行实体  bool start(); //开始执行线程  pthread_t getThreadID(); //获取线程ID  int getState(); //获取线程状态  void join(); //等待线程直至退出  void join(unsigned long millisTime);//等待线程退出或者超时  void detach(); //分离线程private:  pthread_t tid;    //当前线程的线程ID  int threadStatus; //线程的状态  static void* run0(void* pVoid); //获取执行方法的指针  void* run1(); //内部执行方法};
Thread.cpp

#include "Thread.h"void* Thread::run0(void* pVoid){  Thread* p = (Thread*) pVoid;  p->run1();  return p;}void* Thread::run1(){  threadStatus = THREAD_STATUS_RUNNING;  tid = pthread_self();  run();  threadStatus = THREAD_STATUS_EXIT;  tid = 0;  pthread_exit(NULL);}Thread::Thread(){  tid = 0;  threadStatus = THREAD_STATUS_NEW;}Thread::~Thread() {}bool Thread::start(){  return pthread_create(&tid, NULL, run0, this) == 0;}pthread_t Thread::getThreadID(){    return tid;}int Thread::getState(){  return threadStatus;}void Thread::join(){  if (tid > 0){    pthread_join(tid, NULL);  }}void Thread::detach(){  if (tid > 0) {    pthread_detach(tid);  }}void Thread::join(unsigned long millisTime){  if (tid == 0){        return;  }  if (millisTime == 0) {        join();  } else {    unsigned long k = 0;    while (threadStatus != THREAD_STATUS_EXIT && k <= millisTime){      usleep(100);      k++;    }  }}
使用,只需继承Thread类,实现run方法即可:

class WriteThread : public Thread {public:  void run(){};};WriteThread writer;writer.start();writer.detach()



原创粉丝点击