1、helloworld
#include <iostream>
#include <thread>
#include <mutex>
std::mutex display_mutex; //使用互斥锁
void foo(int i){
std::thread::id this_id = std::this_thread::get_id();
display_mutex.lock(); //加锁
std::cout << "thread_func: id = " << this_id << ", " << i << std::endl;
display_mutex.unlock(); //解锁
}
void MultiThread()
{
for (int i = 0; i < 4; i++)
{
std::thread thread(foo, i);
thread.detach(); //回收线程资源(分离式)
std::cout <<std::endl<< "main:" << std::endl;
}
getchar();
return;
}
输出:
thread_func: id = 5960
, main:
0
thread_func: id = 13540, 1
main:
main:
thread_func: id = 7684, 2
thread_func: id = 14252, 3
main:
2、两种方等待线程结束的方式:detach、join
在启动了一个线程(创建了一个thread对象)之后,当这个线程结束的时候,我们如何去回收线程所使用的资源呢?thread库给我们两种选择:加入式(join())和分离式(detach())。值得一提的是,你必须在thread对象销毁之前做出选择,这是因为线程可能在你加入或分离线程之前,就已经结束了,之后如果再去分离它,线程可能会在thread对象销毁之后继续运行下去。
(1)detach这个词的意思是分离的意思,对一个thread对象使用detach()意味着从调用线程分理出这个新的线程,我们称分离的线程叫做守护线程(daemon threads),之后也就不能再与这个线程交互。分离的线程会在后台运行,其所有权(ownership)和控制权将会交给c++运行库。同时,C++运行库保证,当线程退出时,其相关资源的能够正确的回收。
(2)join字面意思是连接一个线程,意味着主动地等待线程的终止,join()是这样工作的:在调用进程中join(),当新的线程终止时,join()会清理相关的资源,然后返回,调用线程再继续向下执行。所以如果对之前的代码再做修改如下:
void MultiThread()
{
for (int i = 0; i < 4; i++)
{
std::thread thread(foo, i);
thread.join(); //回收线程资源(加入式)
std::cout <<std::endl<< "main:" << std::endl;
}
getchar();
return;
}
输出:
thread_func: id = 5692, 0
main:
thread_func: id = 7228, 1
main:
thread_func: id = 3368, 2
main:
thread_func: id = 8180, 3
main: