2

由于我无法控制的原因,我必须使用堆栈大小减小的 pthread。但是,我仍然可以访问 C++11,所以我想写一些类似的东西std::async,让我在分离状态下启动一个 pthread,并运行任何函数,而不返回未来。本质上,std::async 用于返回 void 的函数。

我想出了以下代码,但它真的很难看,我想知道是否有更好的方法来解决这个问题。

static void* thread_start(void* args) {
    // Get the actual function
    std::function<void()>* f_ptr = static_cast<std::function<void()>*>(args);
    // Run the actual function
    (*f_ptr)();
    // Delete the function from the heap
    delete f_ptr;
    // Return nullptr, since we're not dinking around with futures
    return nullptr;
}

template<typename Function, typename... Args>
void async(Function&& f, Args&&... args) {
    static size_t kStackSize = 1024*1024;
    // Allocate a std::function on the heap, so that we can call it safely after this stack frame is destroyed.
    std::function<void()>* f_no_args = new std::function<void()>;
    // Bind Args to Function, so that we have a void function
    *f_no_args = std::bind(f, args...);
    // Set up a new pthread with a smaller stack, and detached
    pthread_attr_t attr;    
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, kStackSize);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_t thread;
    pthread_create(&thread, &attr, &thread_start, f_no_args);
}
4

0 回答 0