1

我可以使用Schwarz counter(又名 Nifty counter)成语thread_local吗?(假设我全部替换staticthread_local

我需要这个(java jni 线程的助手):

class ThisThread{
    JNIEnv* jni_env{nullptr};
public:
    JNIEnv* getEnv(){
        if (!jni_env){
            // Attach thread
            java_vm->GetEnv((void**)&jni_env, JNI_VERSION);
            java_vm->AttachCurrentThread(&jni_env, NULL);
        }

        return jni_env;
    }

    ~ThisThread(){
        if (!jni_env) return;
        // Deattach thread
        java_vm->DetachCurrentThread();
    }
};

static thread_local ThisThread this_thread;

在每个线程中首先构造,最后销毁。我可以this_thread->getEnv()从其他静态或 thread_local 对象的析构函数/构造函数中调用。

更新

https://stackoverflow.com/a/30200992 - 在这里,标准说 thread_local 析构函数在静态之前调用,我需要这个之后。

4

2 回答 2

1

我认为最好的解决方案是正常实现 schwartz 计数器,但以static的形式实现ThisThread类。thread_localImpl

带有输出的完整示例:

// header file
#include <memory>
#include <mutex>
#include <iostream>
#include <thread>

std::mutex emit_mutex;

template<class...Ts>
void emit(Ts&&...ts)
{
    auto action = [](auto&&x) { std::cout << x; };
    auto lock = std::unique_lock<std::mutex>(emit_mutex);

    using expand = int[];
    expand{ 0,
        (action(std::forward<Ts>(ts)), 0)...
    };
}


struct ThisThread
{
    struct Impl
    {
        Impl()
        {
            emit("ThisThread created on thread ", std::this_thread::get_id(), '\n');
        }
        ~Impl()
        {
            emit("ThisThread destroyed on thread ", std::this_thread::get_id(), '\n');
        }
        void foo() 
        { 
            emit("foo on thread ", std::this_thread::get_id(), '\n');
        }
    };

    decltype(auto) foo() { return get_impl().foo(); }

private:
    static Impl& get_impl() { return impl_; }
    static thread_local Impl impl_;
};

struct ThisThreadInit
{

    ThisThreadInit();
    ~ThisThreadInit();

    static int initialised;
};

extern ThisThread& thisThread;
static ThisThreadInit thisThreadInit;



// cppfile

static std::aligned_storage_t<sizeof(ThisThread), alignof(ThisThread)> storage;
ThisThread& thisThread = *reinterpret_cast<ThisThread*>(std::addressof(storage));
int ThisThreadInit::initialised;
thread_local ThisThread::Impl ThisThread::impl_;

ThisThreadInit::ThisThreadInit()
{
    if (0 == initialised++)
    {
        new (std::addressof(storage)) ThisThread ();    
    }
}

ThisThreadInit::~ThisThreadInit()
{
    if (0 == --initialised)
    {
        thisThread.~ThisThread();
    }
}


// now use the object

#include <thread>

int main()
{
    thisThread.foo();

    auto t = std::thread([]{ thisThread.foo(); });
    t.join();
}

示例输出:

ThisThread created on thread 140475785611072
foo on thread 140475785611072
ThisThread created on thread 140475768067840
foo on thread 140475768067840
ThisThread destroyed on thread 140475768067840
ThisThread destroyed on thread 140475785611072
于 2017-11-10T11:40:20.430 回答
0

这没有回答如何让 Schwarz 对抗thread_local static's (所以我不接受这个作为答案)。但最后,我想出了这个平台相关(Linux/Android)的解决方案。

#include <jni.h>
#include <cassert>
#include "JavaVM.h"

namespace jni_interface{

    class ThisThread{
        inline static thread_local pthread_key_t p_key;

        static void pthread_dstr(void *arg){
            if (!jni_env) return;
            java_vm->DetachCurrentThread();
            jni_env = nullptr;

            pthread_setspecific(p_key, NULL);
            pthread_key_delete(p_key);
        }

        static void register_dstr(void *arg){
            {
                const int res = pthread_key_create(&p_key, pthread_dstr);
                assert(res != EAGAIN);
                assert(res != ENOMEM);
                assert(res == 0);
            }
            {
                const int res = pthread_setspecific(p_key, arg);
                assert(res == 0);
            }
        }

        inline static thread_local JNIEnv* jni_env{nullptr};
    public:
        JNIEnv* getEnv(){
            if (!jni_env){
                assert(java_vm);
                java_vm->GetEnv((void**)&jni_env, JNI_VERSION);
                java_vm->AttachCurrentThread(&jni_env, NULL);       // safe to call in main thread

                register_dstr(jni_env);
            }

            return jni_env;
        }
    };

    static thread_local ThisThread this_thread;
}

即使由于某种原因,pthread_dstr将在 C++ 的静态 thread_locals(或交错)之前调用 [换句话说ThisThread,在上次使用前销毁],在下一次调用 object ( getEnv()) 时,我们有点重新初始化/重新创建它并注册pthread_dstr另一轮。

注意,我们最多可以进行PTHREAD_DESTRUCTOR_ITERATIONS轮次,即 4 轮。但在最坏的情况下,我们总是会结束第二轮(如果 C++ thread_local 实现将使用 p_thread 析构函数 [这意味着 OURpthread_dstr可能不会在第一次调用圆形的])。

于 2017-11-11T12:04:07.917 回答