4

enter image description hereIn the code below, I have a parallel section where each thread uses a private vector<int> to push and pop integers. The problem I have is that as I increase the number of threads, the performance of each core decreases drastically, and the Kernel CPU usage (red bar in the htop command) assigned to each core increases a lot. For example, with 1 core I have 100% normal CPU usage, but with 25 cores (see image) almost all the CPU usage goes to the kernel.

It is probably something very basic, but I just don't know why it happens. I would expect that since each thread has its own private variable each core would work exactly the same no matter the number of total CPUS used in the parallel section.

Any advise?

int cpus = 25;
#pragma omp parallel for schedule(dynamic,1)
for (int ss = 0; ss < cpus; ss++)
{
    std::vector<int> q;
    while (true)
    {
        q.push_back(rand());
        q.pop_back();
    }
}
SandiaDeDia
  • 291
  • 2
  • 9
  • 3
    https://stackoverflow.com/questions/6161322/using-stdlibs-rand-from-multiple-threads – Mat Aug 19 '20 at 07:24
  • 6
    https://en.cppreference.com/w/cpp/numeric/random/rand: "It is implementation-defined whether rand() is thread-safe." - using stuff from `` is probably better. – Mat Aug 19 '20 at 07:26
  • Thank you all!!!! yes, I just tried removing the random and it is working. – SandiaDeDia Aug 19 '20 at 07:28
  • 2
    `rand` can either be not thread-safe, which makes your program undefined, or thread-safe, which makes your program non-parallel. (I suspect that the program spends all that kernel time waiting for it.) – molbdnilo Aug 19 '20 at 07:29
  • The GLIBC implementation of `rand()` is not thread-safe. – Hristo Iliev Aug 19 '20 at 08:00
  • Are you sure your while (1) does anything? I can imagine a clever compiler just optimize away a push_back followed by a pop_back. – akira hinoshiro Aug 19 '20 at 08:10
  • I know it execute those lines @akirahinoshiro because the rand issues. – SandiaDeDia Aug 19 '20 at 08:22
  • how can I close the question selecting a comment as the answer?? do I have to answer it myself? – SandiaDeDia Aug 19 '20 at 08:23

0 Answers0