之前写的多线程都是在主进程中调用线程的API,这里为每一个线程封装成一个类;创建了一个线程对象,也就是创建了一个线程;
MyThread.h
/*************************************************************************
> File Name: MyThread.h
> Author:
> Mail:
> Created Time: 2015年12月14日 星期一 16时23分17秒
************************************************************************/
#ifndef _MYTHREAD_H
#define _MYTHREAD_H
#include <iostream>
#include <pthread.h>
#include <string>
using std::string;
class MyThread{
public:
MyThread();
~MyThread();
void set_name(string name);
string get_name();
pthread_t get_pid();
void run(void *(*fun)(void *), void *arg);
void join();
void do_something();//not use
friend void * thread_routine(void *arg);//not use
private:
pthread_t pid;
string thread_name;
};
#endif
MyThread.cpp
/*************************************************************************
> File Name: MyThread.cpp
> Author:
> Mail:
> Created Time: 2015年12月14日 星期一 16时31分43秒
************************************************************************/
#include "MyThread.h"
using namespace std;
MyThread::MyThread()
{
}
MyThread::~MyThread()
{
pthread_join(pid, NULL);
}
void MyThread::set_name(string name)
{
thread_name = name;
}
string MyThread::get_name()
{
return thread_name;
}
pthread_t MyThread::get_pid()
{
return pid;
}
void MyThread::run(void *(*fun)(void *), void *arg)
{
pthread_create(&pid, NULL, fun, arg);
}
void MyThread::join()
{
pthread_join(pid, NULL);
}
/*not use*/
void MyThread::do_something()
{
cout << "thread id is " << pid << ", name is " << thread_name << endl;
}
/*not use*/
void * thread_routine(void *arg)
{
MyThread * pthread;
pthread = static_cast<MyThread *>(arg);
pthread->do_something();
return NULL;
}
main.cpp
/*************************************************************************
> File Name: main.cpp
> Author:
> Mail:
> Created Time: 2015年12月14日 星期一 16时13分21秒
************************************************************************/
#include <cstdlib>
#include <string.h>
#include "MyThread.h"
using namespace std;
void *thread_fun(void * arg)
{
cout << "this is thread routine..." << endl;
return NULL;
}
int main(int argc, char *argv[])
{
int i = 0, num = 0;
if (argc != 2){
cout << "input the number of thread object you want to create...." << endl;
exit(-1);
}
num = atoi(argv[1]);
MyThread thread[num];
cout << "I will create " << num << " threads." << endl;
for (i = 0; i < num; ++i){
thread[i].set_name("thread");
}
for(i = 0; i < num; ++i){
thread[i].run(thread_fun, NULL);
cout << thread[i].get_name() << " pid is " << thread[i].get_pid() << " is running.." << endl;
}
for(i = 0; i < num; ++i){
thread[i].join();
}
cout << "main thread exit....." << endl;
exit(0);
}

本文介绍如何将pthread_create多线程API封装到一个线程类中,以便更方便地创建和管理线程。通过创建线程对象,可以实现对线程的封装和抽象。
176

被折叠的 条评论
为什么被折叠?



