C++11中的多线程(1)

创建线程

​

#include <iostream>
#include <thread>

void thread_function()
{
    std::cout << "thread function\n";
}

int main()
{
    std::thread t(&thread_function);   // t starts running
    std::cout << "main thread\n";
    t.join();   // main thread waits for the thread t to finish
    return 0;
}

[点击并拖拽以移动]
​

输出

thread function
main thread

但是也可能顺序是颠倒的。

join()的意思是让主线程(?)等待子线程执行完成。如果不等待子线程完成,主线程将会继续执行到main函数结束,有可能子线程根本没有机会运行。

当主线程等待的时候,它是空转的(idling)。事实上,操作系统会从主线程剥夺CPU。

 

当子线程通过std::thread t 创建的时候,可能会有创建线程的开销(可以通过使用线程池减小开销)。下图的虚线表示了一种可能的阻塞状态。

 

 

分离线程(detach)

可以通过如下方式让线程是自由运行(run free)的,即成为守护进程(daemon process)

int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    // t.join();
    t.detach();
    return 0;
}

输出是
main thread

分离的线程没有打印自己的输出,因为主线程已经结束并退出了。

这是多线程编程的一个特性:我们不确定哪个线程先运行。(除非使用了同步机制)

就上例而言,因为创建新线程的时间消耗,主线程很可能在子线程之前就结束了。

 

一旦一个线程分离,不能强制它再加入到主线程中。所以如下程序会崩溃

int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    // t.join();
    t.detach();
    t.join();   // Error
    return 0;
}

我们可以通过使用joinable()检查来避免程序崩溃。如果线程不是joinable的,将不会调用join()。

int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    // t.join();
    if(t.joinable()) 
        t.join(); 
    return 0;
}

 

可调用对象(Callable Objects)

之前的例子中,线程使用的是常规函数。事实上,我们可以使用任何可调用的对象,比如lambda函数。

#include <iostream>
#include <thread>

class MyFunctor
{
public:
    void operator()() {
        std::cout << "functor\n";
    }
};

int main()
{
    MyFunctor fnctor;
    std::thread t(fnctor);
    std::cout << "main thread\n";
    t.join();
    return 0;
}

上图中我们新建了一个函数对象,然后把它分配给了一个线程。

下面这种动态传递实例的方法无法通过编译。

// MyFunctor fnctor;
std::thread t(MyFunctor());    // error

但我们给MyFunctor()外层加上个括号就可以了(相关内容是函数声明约定)

// MyFunctor fnctor;
std::thread t((MyFunctor()));    // ok

 

Lambda函数创建线程

int main()
{
    std::thread t([]()
    {
        std::cout << "thread function\n";
    }
    );
    std::cout << "main thread\n";
    t.join();     // main thread waits for t to finish
    return 0;
}

 

向线程传递参数

#include <iostream>
#include <thread>
#include <string>

void thread_function(std::string s)
{
    std::cout << "thread function ";
    std::cout << "message is = " << s << std::endl;
}

int main()
{
    std::string s = "Kathy Perry";
    std::thread t(&thread_function, s);
    std::cout << "main thread message = " << s << std::endl;
    t.join();
    return 0;
}



输出
thread function message is = Kathy Perry
main thread message = Kathy Perry

通过输出我们可以看到string已经传递给了线程。

如果要传递一个引用类型,通过void thread_function(std::string &s) 依然是按值传递的。应该使用std::ref()

std::thread t(&thread_function, std::ref(s));

另外一种不产生拷贝、不共享内存的参数传递方式是使用move()

std::thread t(&thread_function, std::move(s));

由于string从主线程移动(move)到了子线程,所以主线程的输出就没有内容了。打印结果如下:

thread function message is = Kathy Perry
main thread message =

 

线程拷贝和移动(copy move)

如下的拷贝std::thread t2 = t; 不会成功。但是可以通过move转移所有权。

#include <iostream>
#include <thread>

void thread_function()
{
    std::cout << "thread function\n";
}

int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    std::thread t2 = t;  // erroe
    std::thread t2 = move(t);    // ok

    t2.join();

    return 0;
}

 

线程id

可以通过使用this_thread::get_id() 获得线程的id信息。

int main()
{
    std::string s = "Kathy Perry";
    std::thread t(&thread_function, std::move(s));
    std::cout << "main thread message = " << s << std::endl;

    std::cout << "main thread id = " << std::this_thread::get_id() << std::endl;
    std::cout << "child thread id = " << t.get_id() << std::endl;

    t.join();
    return 0;
}

输出
thread function message is = Kathy Perry
main thread message =
main thread id = 1208
child thread id = 5224

可以通过std::thread::hardware_concurrency() 获取线程数量,输出Number of threads = 2

int main()
{
    std::cout << "Number of threads = " 
              <<  std::thread::hardware_concurrency() << std::endl;
    return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值