Lambda C++ 中的持久存储

Persistent storage in Lambda C++

我想创建一个可以在调用之间存储中间数据的 lambda。这是可能的吗?即使在打印存储令牌后,我也从未点击过持久令牌。

auto process   = [&in, &out, callback, tokens = std::deque<O>{}]() mutable {
            // Debug this is never reached
            if (!tokens.empty()) {
                 printf("Tokens Persisted: %u\n",token.size());
            }
            // Populate with new tokens
            if(tokens.empty() && in.ReadValid()) {
                auto new_tokens = callback(in.Read());
                tokens.insert(tokens.begin(), new_tokens.begin(), new_tokens.end());
            }
            // Drain the tokens
            while (!tokens.empty() && out.WriteValid()) {
                out.Write(tokens.front());
                tokens.pop_front();
            }
            // Debug should be hit if we couldn't all write tokens out
            if (!tokens.empty()) {
                    printf("Storing Tokens %u\n", tokens.size());
            }
        };

您可以使用 static 变量来存储您希望在不同调用之间保留的状态,如下所示。下面给出了一个简化的示例(因为您的原始示例对于问题的目的来说不必要地复杂):

auto callable = []()->int{
    static int state = 4;
    std::cout<<"state: "<<state<<std::endl;
    ++state;
    return state;
     
    };
int main()
{
    callable();//prints 4
    callable();//prints 5
    callable();//prints 6
   
}

另一种解决方案,使用可变 lambda(多线程不需要静态变量更好):

#include <iostream>

auto callable = [state = 4]() mutable ->int{
    std::cout<<"state: "<<state<<std::endl;
    ++state;
    return state;     
    };

int main()
{
    callable();//prints 4
    callable();//prints 5
    callable();//prints 6  
}

我通过创建 shared_ptr 并将其传递到进程 lambda 中实现了我想要的。这允许每个进程的创建都有一个唯一的缓冲区,它可以在外部背压的情况下存储结果。

auto t = std::make_shared<std::deque<O>>();
auto process   = [&in, &out, callback, tokens = t]() mutable {
            // Debug this is never reached
            if (!tokens->empty()) {
                 printf("Tokens Persisted: %u\n",token->size());
            }
            // Populate with new tokens
            if(tokens->empty() && in.ReadValid()) {
                auto new_tokens = callback(in.Read());
                tokens->insert(tokens->begin(), new_tokens.begin(), new_tokens.end());
            }
            // Drain the tokens
            while (!tokens->empty() && out.WriteValid()) {
                out.Write(tokens->front());
                tokens->pop_front();
            }
            // Debug should be hit if we couldn't all write tokens out
            if (!tokens->empty()) {
                    printf("Storing Tokens %u\n", tokens->size());
            }
        };