gpt4 book ai didi

c++ - 如何授予Boost Pool访问GSL矩阵以执行任务的线程

转载 作者:行者123 更新时间:2023-12-02 10:12:46 25 4
gpt4 key购买 nike

我有一个gsl矩阵,我要一遍又一遍地填充它,而且要在一个线程上完成所有操作,它的负担很重。是否可以在增强池线程中修改gsl矩阵?

#include <gsl/gsl_linalg.h>
#include <boost/asio.hpp>

int main() {
int SIZE = 3; // small size
gsl_matrix * _A = gsl_matrix_alloc(SIZE, SIZE); // set the gsl matrix to 3x3
gsl_matrix_set_all(_A, 0); // make them all 0 to provide contrast if value changes
auto _dostuff = [&_A]() {
gsl_matrix_set (_A, 0, 0, 20); // set the (0, 0) position to 20
};
boost::asio::thread_pool pool(1); // open up a thread pool containing 1 thread
boost::asio::post(pool, [&_A, &_dostuff]{_dostuff() ;}); // post a task to the pool
std::cout << gsl_matrix_get (_A, 0, 0) << std::endl; // check to see if the (0, 0) position is 20 (its not)

return 0;
}

您将需要在Cmake中添加以下几行
SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++17 -pthread")
find_package(GSL REQUIRED)
target_link_libraries(<folder name> GSL::gsl GSL::gslcblas)
感谢您的时间。

最佳答案

所有线程始终“有权”访问整个进程空间-即该进程在内存中的所有对象。
原则上,不需要“授予X访问权限”。
这里:

post(pool, [&_A, &_dostuff] { _dostuff(); }); // post a task to the pool
您太冗长,可能表示您感到困惑。 _dostuff已经捕获了矩阵,因此您不需要它。另外,如果需要捕获lambda,则可以按值进行捕获(通常是更安全的默认值,尤其是在线程化时):
post(pool, [=] { _dostuff(); });
具有讽刺意味的是,您只需将其替换为
post(pool, _dostuff);
为什么不起作用?
好吧。您只需要检查数据竞赛-一切都会发生( https://en.wikipedia.org/wiki/Undefined_behavior)。
为了获得可靠的检查,您可以先加入线程池:
#include <boost/asio.hpp>
#include <gsl/gsl_linalg.h>
#include <iostream>

namespace ba = boost::asio;

int main() {
int SIZE = 3; // small size
gsl_matrix* _A = gsl_matrix_alloc(SIZE, SIZE); // 3x3
gsl_matrix_set_all(_A, 0); // zero for reference

auto _dostuff = [_A]() {
gsl_matrix_set(_A, 0, 0, 20); // set (0, 0) to 20
};

ba::thread_pool pool(1); // one thread
post(pool, _dostuff); // post task
pool.join();

std::cout
<< gsl_matrix_get(_A, 0, 0)
<< std::endl;

gsl_matrix_free(_A);
}
版画
20
(还修复了内存泄漏)。
注意事项:
您可能要使用 future 来同步任务。还要注意,不必通过引用捕获指针。

关于c++ - 如何授予Boost Pool访问GSL矩阵以执行任务的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62945070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com