posix多线程(linux):
介绍:
NULL
头文件:
pthread.h
相关函数:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
函数传入值:
thread: pthread_t类型的线程标识
pthread_attr_t:线程属性
start_routine:线程函数,必须定义为 void *func(void *arg),如果是类成员作为线程函数,必须是静态的。不接受boost中的函数对象
arg:线程函数的参数,如果是多个,打包成一个结构体,传入结构体指针
函数返回值:
成功:0
失败:其他
使用形式:
void *func1(void *arg) {}
pthread_t t1, t2;
pthread_create(&t1, NULL, func1, NULL);
void *func2(int a, int b) {}
struct Arg {int a, int b};
struct Arg arg = {10, 20};
pthread_create(&t2, NULL, func2, &arg);
boost 线程:
介绍:
创建后即开始执行,线程函数接受任意形式的普通函数、类成员函数,可以使用boost::bind和 boost::function
头文件:
boost/thread.hpp
数据类型:
thread
相关函数
thread(F f, A1 a1, A2 a2, ...); //最多9个参数
join();
timed_join()const system_time &wait_until;
interrupt(); //只有在中断点才可以被中断
static yield();
函数传入值:
f:可执行函数、函数指针,函数对象
aN:线程函数的参数
函数返回值:
无
使用形式:
int func(int a, int b) {}
thread(func, 10, 20); //使用临时对象,无法用join
thread t(func, 10, 20); //可以用对象调用方法
t.join();
boost 线程组:
介绍:
类似线程池
头文件:
boost/thread.hpp
数据类型:
boost::thread_group
相关函数:
thread* create_thread(F threadfunc);
void add_thread(thread *thrd);
void remove_thread(thread *thrd);
void join_all();
void interrupt_all(); //只有在中断点才可以被中断
int size();
函数传入值:
threadfunc:必须是 boost::bind的返回值或者 boost::function对象
thrd:线程对象指针
函数返回值:
无
使用形式:
int func1(int a, int b);
class A {
public:
int func2(int a, string str);
};
A a;
thread_group threads;
threads.create_thread(bind(func1, 10, 20)); //这样是错的:threads.create_thread(func1, 10, 20);
threads.create_thread(bind(&A::func2, &a, "hello", 10)); // &a, ref(a), a
threads.join_all();
其他:
使用 thread_group和 singleton_default可以建立一个类似全局线程池的对象,统一管理程序中的thread:
typedef singleton_default<thread_group> thread_pool;
thread_pool::instance().create_thread(...);