Arrange to generate different random sequences in the different child
authorTom Lane <[email protected]>
Fri, 11 Dec 2009 21:50:06 +0000 (21:50 +0000)
committerTom Lane <[email protected]>
Fri, 11 Dec 2009 21:50:06 +0000 (21:50 +0000)
processes of a pgbench run, when we are using -j > 1 and are emulating
threads via fork().  Otherwise the children all inherit the same random
sequence state and produce the same random-number sequence.

In the threaded case the different threads will share one RNG state, so
they will produce different subsets of one sequence, which is maybe more
correlated than a purist would like but will not be "the same".  So we
leave that case alone.

First noticed by Takahiro Itagaki, and is also part of the explanation
for the pgbench misbehavior recently reported by Jaime Casanova.

contrib/pgbench/pgbench.c

index 8a6437fa9248d26b8d1d0778ffefd3229981f564..cc5fe87d41925598debb6de123d8e39b249fa743 100644 (file)
@@ -1916,7 +1916,7 @@ main(int argc, char **argv)
    INSTR_TIME_SET_CURRENT(start_time);
    srandom((unsigned int) INSTR_TIME_GET_MICROSEC(start_time));
 
-   /* process bultin SQL scripts */
+   /* process builtin SQL scripts */
    switch (ttype)
    {
        case 0:
@@ -2201,6 +2201,7 @@ pthread_create(pthread_t *thread,
 {
    fork_pthread   *th;
    void           *ret;
+   instr_time      start_time;
 
    th = (fork_pthread *) malloc(sizeof(fork_pthread));
    pipe(th->pipes);
@@ -2211,20 +2212,31 @@ pthread_create(pthread_t *thread,
        free(th);
        return errno;
    }
-   if (th->pid != 0)   /* parent process */
+   if (th->pid != 0)   /* in parent process */
    {
        close(th->pipes[1]);
        *thread = th;
        return 0;
    }
 
-   /* child process */
+   /* in child process */
    close(th->pipes[0]);
 
    /* set alarm again because the child does not inherit timers */
    if (duration > 0)
        setalarm(duration);
 
+   /*
+    * Set a different random seed in each child process.  Otherwise they
+    * all inherit the parent's state and generate the same "random"
+    * sequence.  (In the threaded case, the different threads will obtain
+    * subsets of the output of a single random() sequence, which should be
+    * okay for our purposes.)
+    */
+   INSTR_TIME_SET_CURRENT(start_time);
+   srandom(((unsigned int) INSTR_TIME_GET_MICROSEC(start_time)) +
+           ((unsigned int) getpid()));
+
    ret = start_routine(arg);
    write(th->pipes[1], ret, sizeof(TResult));
    close(th->pipes[1]);