# How can I distribute redefinitions of system functions to parallel kernels?

I'm having some trouble getting my parallel kernels to get wind of user redefinitions of system packages, and I'm looking for the cleanest way to do this - preferably using DistributeDefinitions.

To take an example, suppose I want to improve Mathematica's pseudorandom number generator, so I jump in and I redefine it as

Unprotect[RandomInteger];
RandomInteger[] = 4 ; (*chosen by fair dice roll.*)
(*guaranteed to be random.*)
Protect[RandomInteger];


(I actually want to do this in a parallelized environment using the built-in RNG, but it's the same thing.) This works just dandy:

Table[
RandomInteger[]
, {j, 1, 10}]

(*{4, 4, 4, 4, 4, 4, 4, 4, 4, 4}*)


However, if I try to parallelize this, it no longer works as well.

ParallelTable[
RandomInteger[]
, {j, 1, 10}]

(*{1, 1, 0, 1, 1, 0, 0, 0, 1, 1}*)


To add on the second part of the structure, I actually want to do this from inside a package (this one, to be specific). So, suppose I write

BeginPackage["xkcd"];
xkcdRandom[] = 4;

Unprotect[RandomInteger];
RandomInteger[] = 4 ;  (*chosen by fair dice roll.*)
(*guaranteed to be random.*)
Protect[RandomInteger];
EndPackage[];


with xkcdRandom put in just to file in xkcd as a nonempty context. Doing this, I get

Table[
RandomInteger[]
, {j, 1, 10}]

(*{4, 4, 4, 4, 4, 4, 4, 4, 4, 4}*)


and so far so good, and parallelizing it we have

ParallelTable[
RandomInteger[]
, {j, 1, 10}]

(*{1, 1, 0, 1, 1, 0, 0, 0, 1, 1}*)


as before, but now I can jump in again and say

DistributeDefinitions["xkcd"];


and try again, but I still get

ParallelTable[
RandomInteger[]
, {j, 1, 10}]

(*{1, 1, 1, 1, 0, 0, 1, 1, 0, 0}*)


OK, then, so RandomInteger is inside the package but it is still part of the System context, which is fair enough, but then if I write

DistributeDefinitions["System"]


I still get

ParallelTable[
RandomInteger[]
, {j, 1, 10}]

(*{1, 1, 1, 1, 1, 0, 0, 1, 1, 0}*)


and even with an explicit

DistributeDefinitions[RandomInteger]


it still doesn't work

ParallelTable[
RandomInteger[]
, {j, 1, 10}]

(*{1, 0, 1, 0, 0, 0, 0, 1, 1, 0}*)


Now, I know I can simply run my specific redefinition inside a ParallelEvaluate command, but ideally I would like to simply have my .m file run a DistributeDefinitions on my package at the end of the file (after the End[]` of the package) and forget about it on the user side, which has otherwise worked perfectly. Is there a way to extend that workflow to redefinitions like this one?

• maybe SetSharedVariable – Wjx Jul 19 '16 at 15:47