I created this program. It does nothing of interest but use processing power.
Looking at the output with objdump -d
, I can see the three rand
calls and corresponding mov
instructions near the end even when compiling with O3 .
Why doesn't the compiler realize that memory isn't going to be used and just replace the bottom half with while(1){}
? I'm using gcc
, but I'm mostly interested in what is required by the standard.
/*
* Create a program that does nothing except slow down the computer.
*/
#include <cstdlib>
#include <unistd.h>
int getRand(int max) {
return rand() % max;
}
int main() {
for (int thread = 0; thread < 5; thread++) {
fork();
}
int len = 1000;
int *garbage = (int*)malloc(sizeof(int)*len);
for (int x = 0; x < len; x++) {
garbage[x] = x;
}
while (true) {
garbage[getRand(len)] = garbage[getRand(len)] - garbage[getRand(len)];
}
}
g++ -O3 slowdown.cc
is the full command I'm using.rand()
, which this one doesn't.fork()
doesn't create multiple threads. It creates a new separate full-fledged process. Their memory is shared copy-on-write, not read-write shared like threads share memory. On Linux, glibc'sfork()
implementation usesclone()
, but with different flags than for thread creation. So the multiple processes each have their own RNG state forrand()
. Even if they were shared-memory threads, they each do their own malloc.fork()
loop doesn't check that it's the parent before going on to the next iteration. So you're actually spawning 2^5 (32) infinite-loop processes. Each trip through the loop is a doubling in the number of processes.