ope*_*ind 7 c++ multithreading c++11 c++14
在书里
Anthony Williams的“ C ++并发性”
您可以找到以下两个代码段(我进行了一些细微的修改):
片段1:
class thread_guard
{
std::thread& t;
public:
explicit thread_guard(std::thread& t_): t(t_){}
~thread_guard()
{
if(t.joinable())
{
t.join();
}
}
thread_guard(thread_guard const&)=delete;
thread_guard& operator=(thread_guard const&)=delete;
};
void my_func()
{
for(int j = 0; j < 1000; ++j)
{
cout << "\n " << j;
}
}
void f()
{
std::thread t1(my_func);
thread_guard g(t1);
do_something_in_current_thread();
}
int main()
{
f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
继续你可以找到
片段2:
class scoped_thread
{
std::thread t;
public:
explicit scoped_thread(std::thread t_): t(std::move(t_))
{
if(!t.joinable())
throw std::logic_error(“No thread”);
}
~scoped_thread()
{
t.join();
}
scoped_thread(scoped_thread const&)=delete;
scoped_thread& operator=(scoped_thread const&)=delete;
};
void my_func()
{
for(int j = 0; j < 1000; ++j)
{
cout << "\n " << j;
}
}
void f()
{
scoped_thread st1(thread(my_func));
thread t2(my_func);
scoped_thread st2(move(t2));
do_something_in_current_thread();
}
int main()
{
f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不确定我是否真的可以欣赏这两个摘要之间的真正区别。
我可以看到的唯一区别是,在代码片段1中,的实例thread_guard不拥有线程的所有权t1(与scoped_thread对象不同),因此可以进行调用,t1.join()但这在~thread_guard()执行时不是问题。
那么:Snippet 2的优势在哪里(如果存在)?
这两种类型都将阻止破坏(例如,范围退出),直到线程完成。不同之处在于thread对象的所有权。
thread_guard不拥有thread自己 可能有一个以上的thread_guard等待thread。这也意味着thread只要任何对象thread_guard引用该对象,该对象就必须是活动的。如果thread_guard销毁对象时已引用的线程已经加入,则不会阻塞或产生错误(与仅调用join不可连接的线程相反)。
scoped_thread另一方面,获得thread实例的所有权,因此也控制了实例的生存期。只要您想拥有要等待的线程(例如,作为数据成员),就可以使用它。
最终,您使用的是一个语义问题:您要等待别人拥有的线程(然后还必须确保不存在生命周期问题),还是想要一个thread对象在销毁时阻塞? ,而无需您join先进行操作。
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |