wrathematics / Romp

Basic examples using OpenMP with R, for C, C++, F77, and Fortran 2003.
Other
44 stars 6 forks source link

Output of `rcpp_hello()` #2

Open sn248 opened 5 years ago

sn248 commented 5 years ago

Hi

I am getting the following output on executing Romp::rcpp_hello()

Hello from thread Hello from thread Hello from thread Hello from thread Hello from thread 00Hello from thread Hello from thread Hello from thread 00 of 0 of 000 of  of 1 of  of  of 1 of 11

1
1

11

I am using R version 3.5.0 on macOS Mojave. Thank you for your package!

sn248 commented 5 years ago

Sorry, forgot to ask - is that expected output? I am assuming that I was supposed to get Hello from thread and then thread number (not in order) in a separate line. Thanks!

wrathematics commented 5 years ago

I'm a little confused why each thread seems to think it's thread 0 in your case. Here's what I see when I run it:

Romp::rcpp_hello()
## Hello from thread Hello from thread Hello from thread 32 of  of 04
## Hello from thread 1 of 4
##  of 4
## 4

If you want it to print neatly (which will break the parallelism - it's basically a more complicated serial program at that point) you can add a barrier:

library(Rcpp)

code = '
#include <omp.h>
#include <Rcpp.h>

// [[Rcpp::export]]
void rcpp_hello_barrier()
{
  int tid, nthreads;

  #pragma omp parallel default(shared) private(tid, nthreads)
  {
    tid = omp_get_thread_num();
    nthreads = omp_get_num_threads();

    for (int id=0; id<nthreads; id++)
    {
      if (id == tid)
        Rcpp::Rcout << "Hello from thread " << tid << " of " << nthreads << std::endl;

      #pragma omp barrier
    }
  }
}
'

Sys.setenv("PKG_CXXFLAGS" = "-fopenmp")
sourceCpp(code=code)
rcpp_hello_barrier()

When I run that, I get

rcpp_hello_barrier()
## Hello from thread 0 of 4
## Hello from thread 1 of 4
## Hello from thread 2 of 4
## Hello from thread 3 of 4

Could you run the one with the barrier and show me the output?

sn248 commented 5 years ago

Thank you very much for your reply. I apologize for my late answer..but it seems adding barrier works, here is my output

Hello from thread 0 of 8
Hello from thread 1 of 8
Hello from thread 2 of 8
Hello from thread 3 of 8
Hello from thread 4 of 8
Hello from thread 5 of 8
Hello from thread 6 of 8
Hello from thread 7 of 8

I am going to study your package a bit more to see how I can implement openMP in my package. Thanks.