您的位置:首页 > 其它

第二章(基本线程管理)

2015-07-06 12:40 309 查看
1、启动线程

1.1 全局函数启动(下面以线程调用该接口进行说明)

void TestFunction()

{

 

}

void TestFun1()

{

    thread my_thread1(TestFunction);

    assert(my_thread1.joinable()); // my_thread1没有被任何线程关联,它是可以被关联的。内部实现是根据thread的id是否为0在进行判断

    my_thread1.join();  // 主线程等待这个线程完成返回

    assert(!my_thread1.joinable()); // 返回后肯定是不可关联的了

    thread my_thread2(TestFunction);

    if (my_thread2.joinable())

    {

        my_thread2.detach();  // detach,让任何线程都无法join到它。即将该线程的id置为0

    }

    assert(!my_thread2.joinable());

}

简单看下joinable的实现

bool joinable() const _NOEXCEPT

  { 

    // return true if this thread can be joined

      return (!_Thr_is_null(_Thr));   // #define _Thr_is_null(thr) (thr._Id == 0)

  }

join的实现即将my_thread的线程id保存到调用join函数的线程中,并将my_thread的id设置为0

1.2 全局函数带参数进行调用

void TestFunctionForRefParam(int& i)

{

    ++i;

}

void TestFunctionForParam(int i)

{

    ++i;

}

void TestFun2()

{

    int i = 10;

    // 此方式中,虽然TestFunctionForRefParam参数是引用,但是也是用的临时对象的引用,不是i

    thread my_thread1(TestFunctionForRefParam, i);

    // 使用如下方式可以保证使用i的引用,ref的实现可以参考另外一篇文章(ref源码解析)

    thread my_thread2(TestFunctionForRefParam, ref(i));

    thread my_thread3(TestFunctionForParam, ref(i));

}

1.3 仿函数调用

class CBackgroundTask

{

public:

    CBackgroundTask(long lStopIn)

        : lStop_(lStopIn)

 {}

 void operator()()const

 {

      

 }

private:

 long lStop_;

};

void CThreadManager::TestClass()

{

 CBackgroundTask testClassTask(10);

 thread my_thread1{testClassTask};   

 thread my_thread2{ CBackgroundTask(20) };// 大括号更加明确的表示它是一个对象,而不是一个函数指针之类的,防止编译器错误的理解

 my_thread1.join();

my_thread2.join();

}

1.4 匿名函数lambda表达式

thread thread1([]{dosomething();dosomething2();}); // 创建了一个匿名函数,该函数内部调用两个函数

1.5 成员函数

thread thread1(&TestClass::DoSomeThing(), &MyClass);

1.6 线程的move

thread没有拷贝,赋值等函数,但是支持move

void fThread(thread t)

{

    bool b1 = t.joinable();

    t.join();

}

void CThreadManager::TestThreadMove()

{

    thread t1(TestFunctionForParam, 1);

    thread t2 = std::move(t1);

    //thread t3 = t2;

    bool b1 = t2.joinable();

    bool b2 = t1.joinable();

    long l1 = thread::hardware_concurrency();

    this_thread::get_id();

    t1 = thread(TestFunctionForParam, 2);

    //t1 = move(t2); // 此语句会终止thread.因为t1已经有一个线程所有权了

    fThread(move(t1));

}

1.7 其它

获取线程id

当前线程标示符:std::this_thread::get_id()

获取cpu个数: thread::hardware_concurrency();


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: