The spawn function runs a given function or script in a different
thread.

js&gt; function g() { a = 7; }
js&gt; a = 3;
3
js&gt; spawn(g)
Thread[Thread-1,5,main]
js&gt; a
3
493292
public static Object spawn(Context cx, Scriptable thisObj, Object[] args,
                               Function funObj)
    {
        Scriptable scope = funObj.getParentScope();
        Runner runner;
        if (args.length != 0 && args[0] instanceof Function) {
            Object[] newArgs = null;
            if (args.length > 1 && args[1] instanceof Scriptable) {
                newArgs = cx.getElements((Scriptable) args[1]);
            }
            if (newArgs == null) { newArgs = ScriptRuntime.emptyArgs; }
            runner = new Runner(scope, (Function) args[0], newArgs);
        } else if (args.length != 0 && args[0] instanceof Script) {
            runner = new Runner(scope, (Script) args[0]);
        } else {
            throw reportRuntimeError("msg.spawn.args");
        }
        runner.factory = cx.getFactory();
        Thread thread = new Thread(runner);
        thread.start();
        return thread;
    }
908687
function spawnProtractor(configPath, chunks, port, skyPagesConfig) {
  logger.info('Running Protractor');
  protractorLauncher.init(configPath, {
    params: {
      localUrl: `https://localhost:${port}`,
      chunks: chunks,
      skyPagesConfig: skyPagesConfig
    }
  });
  process.on('exit', killServers);
}
594267
def spawn(mode, func, *args, **kwargs):
    
    if mode is None:
        # 'threading' is the default mode.
        mode = 'threading'
    elif mode not in spawn.modes:
        # validate the given mode.
        raise ValueError('Invalid spawn mode: %s' % mode)
    if mode == 'threading':
        return spawn_thread(func, *args, **kwargs)
    elif mode == 'gevent':
        import gevent
        import gevent.monkey
        gevent.monkey.patch_select()
        gevent.monkey.patch_socket()
        return gevent.spawn(func, *args, **kwargs)
    elif mode == 'eventlet':
        import eventlet
        eventlet.patcher.monkey_patch(select=True, socket=True)
        return eventlet.spawn(func, *args, **kwargs)
    assert False
772391
function runCmd(cmd, args, fn) {
    args = args || [];
    let runner = require('child_process').spawn(cmd, args, {
        // keep color
        stdio: 'inherit',
    });
    runner.on('close', function(code) {
        if (fn) {
            fn(code);
        }
    });
}
1057076
function run(thisArg, args) {
    var end = -1;
    const r = this._f.map((f, i) => {
        if(end === -1) {
            return f.apply(thisArg, args.concat(abort));
        }

        function abort() {
            end = i;
        }
    });
    if(end === -1) {
        return r;
    }
    return r.slice(0, end);
}
117549
def spawn_thread
      Thread.new do
        while true
          x = @queue.shift
          if x == Directive::SUICIDE_PILL
          	@worker_threads_count.decrement
          	Thread.current.terminate
          end
          Thread.pass
          begin
            x.job.call(x)
          rescue StandardError => e
            $stderr.puts "Threadz: Error in thread, but restarting with next job: #{e.inspect}\n#{e.backtrace.join("\n")}"
          end
        end
      end
      @worker_threads_count.increment
    end
1297082
function (args, detached, callback) {
  let error, errorEmitted, stderr, stdout

  try {
    // Ensure we don't spawn multiple squirrel processes
    // Process spawned, same args:        Attach events to alread running process
    // Process spawned, different args:   Return with error
    // No process spawned:                Spawn new process
    if (spawnedProcess && !isSameArgs(args)) {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(`AutoUpdater process with arguments ${args} is already running`)
    } else if (!spawnedProcess) {
      spawnedProcess = spawn(updateExe, args, {
        detached: detached,
        windowsHide: true
      })
      spawnedArgs = args || []
    }
  } catch (error1) {
    error = error1

    // Shouldn't happen, but still guard it.
    process.nextTick(function () {
      return callback(error)
    })
    return
  }
  stdout = ''
  stderr = ''

  spawnedProcess.stdout.on('data', (data) => { stdout += data })
  spawnedProcess.stderr.on('data', (data) => { stderr += data })

  errorEmitted = false
  spawnedProcess.on('error', (error) => {
    errorEmitted = true
    callback(error)
  })

  return spawnedProcess.on('exit', function (code, signal) {
    spawnedProcess = undefined
    spawnedArgs = []

    // We may have already emitted an error.
    if (errorEmitted) {
      return
    }

    // Process terminated with error.
    if (code !== 0) {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`)
    }

    // Success.
    callback(null, stdout)
  })
}
100599
function spawnService(serviceName, type, initWait) {
    // Type can be either service or coreService
    // When coreService, a service from the core-service folder will be spawned
    type = type || 'service';

    // If init wait is set, we will wait for the INITDONE signal before resolving the promise
    initWait = initWait || false;

    // Load the service and return a promise
    return new unicorn.promise(function(resolve, reject){

        if(typeof(serviceName) == 'undefined') reject({msg:'No service name'});

        try {
            // We must fix the hardcoded config path.. or maybe not
            // Maybe change the name of the config to unicorn config and make this default
            var service = Spawn('node', [unicorn.path + '/spawn.js', config.unicornPath + '/config.json', serviceName, type]);

            // Print errors on the console when errors comes in
            service.stderr.on('data', function (data) {
                // Replace newlines, because data is a buffer and will print a newline for free
                console.log(data.toString().replace(/^\s+|\s+$/g, ''));
            });

            // Print info when a process exits
            service.on('close', function (code) {
                console.log('Child process: ' + serviceName + ' exited with code ' + code);
            });

            // Print info when a process exits
            service.on('exit', function (code) {
                console.log('Dirty child process: ' + serviceName + ' exit with code ' + code);
            });

            service.on('error', function (err) {
                console.log('Child process: ' + serviceName + ' error: ' + err);
            });

            // Switch the moment of the resolve, if initWait is enabled we must wait for a return signal
            if(initWait) {
                // Print data on the console when data comes in
                service.stdout.on('data', function (data) {
                    // Replace newlines, because data is a buffer and will print a newline for free
                    var procData = data.toString().replace(/^\s+|\s+$/g, '');

                    // See if we have a system message first, since we cannot use process.send we use std for messaging
                    if (procData == 'INITDONE') {
                        resolve({service: broker, name: broker.name, pid: broker.pid});
                    } else {
                        console.log(procData);
                    }
                });
            } else {
                // Print data on the console when data comes in
                service.stdout.on('data', function (data) {
                    // Replace newlines, because data is a buffer and will print a newline for free
                    console.log(data.toString().replace(/^\s+|\s+$/g, ''));
                });

                resolve({service:service, name:service.name, pid:service.pid});
            }
        } catch (err) {
            reject(err);
        }

    });
}
1121426
def spawn(func, kwargs):
    """"""
    t = threading.Thread(target=func, kwargs=kwargs)
    t.start()
    yield
    t.join()
833309
def spawn_thread(func, *args, **kwargs):
    """"""
    thread = threading.Thread(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread
1073112
function Runnable(title, fn) {
  this.title = title;
  this.fn = fn;
  this.body = (fn || '').toString();
  this.async = fn && fn.length;
  this.sync = !this.async;
  this._timeout = 2000;
  this._slow = 75;
  this._enableTimeouts = true;
  this.timedOut = false;
  this._retries = -1;
  this._currentRetry = 0;
  this.pending = false;
}
1001375
function (i) {
                    workers[i] = cluster.fork();

                    console.log('Creating Worker: ', workers[i].process.pid);
                    workers[i].on('message', m => {
                        switch (m.type) {
                            case 'STARTED':
                                !startedWorkers && startWatches();
                                break;
                        }
                    });
                    // Optional: Restart worker on exit
                    workers[i].on('exit', function (code, signal) {
                        console.log('Respawning worker', i);
                        spawn(i);
                    });
                }
798060
function spawn() {
  if(this.ps && this.ps.connected) return;
  this.ps = fork(
    runner, [], {execPath: path.basename(process.execPath)});
  this.ps.send({event: 'loglevel', level: log.level()});
}
405006
async function crash (reason_, runHooks_, timeout_) {
    const reason = reason_ || 0;
    const runHooks = (typeof runHooks_ !== 'undefined') ? runHooks_ : true
    const timeout = timeout_ || 5000;

    // NOTE: All hooks are stored as promise-returning functions.  This allows
    // this code to be uniform as hell.

    /* Avoid running hooks multiple times */
    const wasCrashed = G.crashed;
    G.crashed = true;

    /* wait for hooks to complete */
    if (runHooks && !wasCrashed) {
        /* Set the timeout */
        setTimeout(crash.bind(null, EXIT_TIMEOUT, false), timeout).unref();

        /* Get all hook promises */
        const promises = G.hooks.map(fn => fn(reason));
        await Promise.settle(promises);
    }

    /* find out the exit code we should use */
    const exitCode = calcExitCode(reason);
    process.exit(exitCode);
}
185219
function WorkingQueue(concurrency) {
    // Parallelization degree, if not mentioned use 64
    // Don't forget that we are in a SINGLE-threaded process
    // All we want it to somewhat limit the number of simultaneous
    // I/O requests
    concurrency = concurrency || 64;


    // The queue contains tuples :
    // [job, arg1, arg2, arg3...]
    var queue = [];
    var workers = 0;
    var onceDoneCallbacks = [];
    var held = false;
    var added = false;

    // This function launches a new worker, if possible
    // It returns true if a new worker was launched, false otherwise.
    function _go() {
        if(workers < concurrency) {
            var job = queue.shift();
            if(job !== undefined) {
                var worker = job.shift();
                job.push(over);
                workers++;
                process.nextTick(function nextTickWorker() {
                    worker.apply(null, job);
                });
                return true;
            }
        }
        return false;
    }

    // This function is passed to each job, it must be called
    // when the job is done.
    function over() {
        workers--;

        if(!held) { _go(); }

        checkDone();
    }

    function checkDone() {
        if(queue.length === 0 && workers === 0) {
            var i, l;

            for(i=0, l=onceDoneCallbacks.length; i < l; i++) {
                process.nextTick(onceDoneCallbacks[i]);
            }

            // Reset callbacks & status
            onceDoneCallbacks = [];
            added = false;
        }
    }

    // Enqueue a new job and ends the current one
    over.then = function overThen(/*...*/) {
        // Since it is only possible to get the over function
        // while running a job, no need to call this.perform
        queue.push(Array.prototype.slice.call(arguments, 0));
        added = true;
        return over();
    };

    // Main method : launches a job immediatly or queue it
    // if maximum number of workers has been reached
    this.perform = function perform(/*...*/) {
        queue.push(Array.prototype.slice.call(arguments, 0));
        added = true;
        if(!held) { _go(); }
        return this;
    };

    // Apply the worker function to each element in the list
    // The worker is in the form function(index, element /*, ...*/, over)
    this.processList = function processList(worker, list /*, ... */) {
        var length = list.length;
        var args, extra;

        if(length>0) {
            extra = Array.prototype.slice.call(arguments, 2);

            for(var i=0;i<length;i++) {
                args = [worker, i, list[i]].concat(extra);
                queue.push(args);
            }

            added = true;
            if(!held) { _go(); }
        }

        return this;
    };

    // Apply the worker function to each element in the dictionary
    // The worker is in the form function(key, value, /*, ... */, over)
    this.processObject = function processObject(worker, dict /*, ... */) {
        var args;
        var extra = Array.prototype.slice.call(arguments, 2);

        for(var key in dict) {
            args = [worker, key, dict[key]].concat(extra);
            queue.push(args);
            added = true;
        }

        if(!held) { _go(); }
        return this;
    };

    // Register a callback that will be called when
    // all jobs have been done.
    // If a callback is registered after the jobs are over,
    // it is called immediatly
    this.onceDone = function onceDone(fun) {
        onceDoneCallbacks.push(fun);
        if(added) { checkDone(); }
    };

    this.whenDone = util.deprecate(this.onceDone, "capisce.WorkingQueue.whenDone is deprecated, use onceDone instead.");

    this.doneAddingJobs = function doneAddingJobs() {
        if(!added) { checkDone(); }
    };

    // Holds the WorkingQueue. No job will be executed until
    // the go() method is called
    this.hold = function hold() {
        held = true;
    };

    // Launches the scheduled jobs
    this.go = function go() {
        if(held) {
            held = false;

            // Loop to launch as many workers as possible
            while(_go()) {}
        }
    };

    // This method is used for a little DSL that can build sequence of
    // jobs, as well as concurrent sections within those sequences.
    this.then = function then(block, concurrency2) {
        if(concurrency>1) { throw 'Cannot use then in a concurrent section'; }

        if(block.length === 1) {
            if(arguments.length !== 1) {
                throw 'Cannot specifiy a concurrency level for sequences';
            }
            this.perform(block);
        } else if(block.length === 2) {
            this.perform(function worker(over) {
                var concurrently = new WorkingQueue(concurrency2);
                block(concurrently, function over2() {
                    concurrently.onceDone(over);
                });
            });
        } else {
            throw 'then accepts building function with one (sequence) or two (concurrent) arguments';
        }

        return this;
    };

    function waiter(timeout, job, over) {
       setTimeout(function waiter() {
            if(job.length>0) {
                var func = job.shift();
                job.push(over);
                return func.apply(null, job);
            }
            else {
                return over();
            }
       }, timeout);
    }

    // This method waits the given timeout then executes the facultative
    // job.
    // This can be used in two ways :
    // sequence().wait(5000).then(function(over) {...})
    // OR
    // sequence().wait(5000,function(over) {...})s
    this.wait = function wait(timeout /*...*/) {
        var job = Array.prototype.slice.call(arguments, 1);
        this.perform(waiter, timeout, job);
        return this;
    };
}
650610
function run (N, op, init) {
  var stats = null, value
  for(var j = 0; j < 100; j++) {
    if(init) value = init(j)
    var start = Date.now()
    for(var i = 0; i < N; i++) op(value, i)
    stats = Stats(stats, N/((Date.now() - start)))
  }
  return stats
}
153987
def _spawn(self):
        
        self.queue = Queue(maxsize=self.num_threads * 10)
        for i in range(self.num_threads):
            t = Thread(target=self._consume)
            t.daemon = True
            t.start()