【问题标题】:Is pybind11 `py::array` object thread-safe?pybind11 `py::array` 对象是线程安全的吗?
【发布时间】:2020-07-09 22:35:06
【问题描述】:

使用<thread> 库,我用C++ 编写了一段由Python 调用的多线程代码,我使用了pybind11 库。代码失败并抛出SIGSEGV 错误,但是,我没有明确编写任何共享资源。

在代码中,我使用了两个 py::arrays 对象,特别是之前存储在 C++ 类中的 py::array 的两个视图。 py::array 保留对 handle 对象的引用,该对象不执行任何引用计数,所以我想在多个线程上使用它是安全的。我说的对吗?

下面是一个简单的例子来更好地说明问题:

MyClass::MyClass(py::array ar) {
    /* perform a reshape of ar */
    this->ar = ar;
}

MyClass::MyMethod() {
    py::gil_scoped_release release;
    /* create threads*/
    /* for each thread, compute two views of ar, ar1 and ar2*/
    /* compute a double using ar1 and ar2 */
    /* use double to update another structure (not py::array)*/
    /* join threads*/
    py::gil_scoped_acquire acquire;
    return 
}

最后,请注意,我更新的结构只是从py::buffer_info 对象中提取的指针,我会注意更新每个线程中的单独部分。

【问题讨论】:

    标签: python c++ multithreading pybind11 gil


    【解决方案1】:

    不知道为什么,对象的数组族显然不是线程安全的。

    当我使用 pybind11 数组和 openMP 时,我总是提取数据指针 ( 使用 data() 和 mutableData() 函数),形状和步幅超出平行区域,并使用平行区域内的数据指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2020-10-03
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多