Lately, I've been using RcppArmadillo
, but I've noticed some inconsistencies in the print order of certain objects. Particularly, when using cout
and print()
. Sometimes, print()
will be printed first, then cout
; and other times it's the other way around.
I do not understand exactly why this is happening. I suppose cout
and print()
are called asynchronously and hence the difference in order, but why is this happening? And how can it be prevented?
Example
If I have the following test_order.cpp
file
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
int test(int n){
cout << "Print 1\n";
arma::mat X(n, n);
cout << "Print 2\n";
X.print();
cout << "Print 3\n";
return 1;
}
And call it from R like this
library(Rcpp)
sourceCpp("test_order.cpp")
test(3)
I get different results when printing. Three different results are the following:
> test(3)
2.1220e-314 0 6.9531e-310Print 1
Print 2
2.3044e-314 6.9275e-310 6.9532e-310
2.1916e-314 2.1916e-314 2.2718e-314
Print 3
[1] 1
> test(3)
Print 1
Print 2
6.9531e-310 2.3044e-314 4.9407e-324
6.9532e-310 2.1916e-314 4.9407e-324
0 6.9275e-310 4.9407e-324
Print 3
[1] 1
> test(3)
6.9531e-310 2.3044e-314 4.9407e-324
6.9532e-310 2.1916e-314 4.9407e-324
0 6.9275e-310 4.9407e-324Print 1
Print 2
[1]Print 3
1