簡體   English   中英

如何在 cppyy 中使用 future / async

[英]How to use future / async in cppyy

我正在嘗試通過 cppyy(一個 C++-python 綁定包)使用 C++ STL 的future
例如,我可以在 C++ 中運行以下代碼(改編自這個答案

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

using namespace std;
using namespace chrono_literals; 

int main () {
    promise<int> p;
    future<int> f = p.get_future();
    thread t([&p]() {
        this_thread::sleep_for(10s);
        p.set_value(2);
    });
    auto status = f.wait_for(10ms);
    if (status == future_status::ready) {
        cout << "task is read" << endl;
    } else {
        cout << "task is running" << endl;
    }
    t.join();
    return 0;
}

Python 中上述的類似實現是

import cppyy

cppyy.cppdef(r'''
#include <future>
#include <thread>
#include <chrono>
#include <iostream>

using namespace std;

int test () {
    promise<int> p;
    future<int> f = p.get_future();
    thread t([&p]() {
        this_thread::sleep_for(10s);
        p.set_value(2);
    });
    auto status = f.wait_for(10ms);
    if (status == future_status::ready) {
        cout << "task is read" << endl;
    } else {
        cout << "task is running" << endl;
    }
    t.join();
    return 0;
}
''')


cppyy.gbl.test()

上面的代碼產生

IncrementalExecutor::executeFunction: symbol '__emutls_v._ZSt15__once_callable' unresolved while linking symbol '__cf_4'!
IncrementalExecutor::executeFunction: symbol '__emutls_v._ZSt11__once_call' unresolved while linking symbol '__cf_4'!

看起來它是由在 cppyy 中使用future引起的。 有什么解決辦法嗎?

Clang9 的 JIT 不支持現代 g++ 實現它的方式的線程本地存儲,將在(正在進行的)Clang13 升級完成時再次檢查,這可能會解決此問題。

否則,cppyy 可以很好地與線程代碼混合(例如,上面的示例在 MacOS 上運行良好,系統編譯器為 Clang)。 只是任何 TLS 的使用都需要放在編譯的庫代碼中,而 JIT 有這個限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM