posix多线程和boost多线程学习笔记

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(...);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值