C++ 为什么在多线程处理时Rcout和Rprintf会导致堆栈限制错误?
因此,在下面的代码中,我使用C++ 为什么在多线程处理时Rcout和Rprintf会导致堆栈限制错误?,c++,r,multithreading,rcpp,C++,R,Multithreading,Rcpp,因此,在下面的代码中,我使用std::thread()来报告程序进度,为了演示这个问题,该示例被修改为以不合理的间隔报告,并显示一条非信息性消息 #include <Rcpp.h> #include <thread> #include <chrono> #include <atomic> using namespace Rcpp; void reporter(const std::atomic<bool> &running)
std::thread()
来报告程序进度,为了演示这个问题,该示例被修改为以不合理的间隔报告,并显示一条非信息性消息
#include <Rcpp.h>
#include <thread>
#include <chrono>
#include <atomic>
using namespace Rcpp;
void reporter(const std::atomic<bool> &running) {
while (running) {
Rprintf( "Program running...\n" );
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
}
// [[Rcpp::export]]
void example() {
int i = 1;
std::atomic<bool> running{true};
std::thread reporter_thread(
[&] () { reporter(running); }
);
while (true) {
i++;
i--;
}
return;
}
所以我有两个问题:
关于你的第一个例子,我必须说: 从线程代码调用任何R API都是“仅供专家使用”:他们需要阅读源代码以确定它是否是线程安全的。特别是,不能从线程化代码中调用使用堆栈检查机制的代码
我不会在线程代码中调用R API函数。我不确定第二个例子,但会首先寻找现有的解决方案,例如如果你想在SCAN上发布STD::CUT是不允许的,你可以考虑保护你的RCUT。
#include <Rcpp.h>
#include <thread>
#include <chrono>
#include <atomic>
using namespace Rcpp;
void reporter(const std::atomic<bool> &running, std::atomic<bool> &print_message) {
while (running) {
std::this_thread::sleep_for(std::chrono::microseconds(10));
print_message = true;
}
}
// [[Rcpp::export]]
void example() {
int i = 1;
std::atomic<bool> running{true};
std::atomic<bool> print_message{true};
std::thread reporter_thread(
[&] () { reporter(running, print_message); }
);
while (true) {
i++;
i--;
if (print_message)
Rprintf( "Program running...\n" );
print_message = false;
}
return;
}