检测螺纹端 [英] Detect thread end

查看:60
本文介绍了检测螺纹端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测线程何时结束(以与平台无关的方式)? 我必须为每个线程存储对象的副本,我想知道什么时候可以处理或重新分发它.

How can I detect when a thread was ended (in a platform independent way)? I have to store copies of objects for every thread and I want to know when I can dispose or redistribute it.

推荐答案

可能是通过RAII和local_thread机制实现的.我们创建一个类,在析构函数中做有用的工作.

It's possibly via RAII and local_thread mechanism. We create a class that do usefull work in destructor.

class ThreadEndNotifer
{
public:
    ~ThreadEndNotifer()
    {
        // Do usefull work
        useFullWork();
    }
}

接下来,我们创建local_thread变量.它可以是全局或类feild(thread_local类字段为隐式静态).

Next, we create local_thread variable. It can be global or class feild(thread_local class field is implicit static).

class Foo 
{
private:
    // Remember about initialization like static feild
    thread_local ThreadEndNotifer mNotifer; 
}

因此,每次线程结束时,都会调用useFullWork. 我喜欢创建一个全局变量并仅在需要时将其初始化,这样可以避免开销.

So, the useFullWork will be called every time when any thread are ending. I like to create one global variable and init it only if needed, in this way I avoid overhead.

这篇关于检测螺纹端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆