How to use threads - 10 common examples

To help you get started, we’ve selected a few threads examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github TypeScriptToLua / TypeScriptToLua / test / threaded_runner.ts View on Github external
console.log("-----------------");
}

config.set({
  basepath: {
    node: __dirname,
  }
});

let cpuCount = os.cpus().length + 1;
if ("TRAVIS" in process.env && "CI" in process.env) {
    // fixed thread count for CI
    cpuCount = 8;
}
const testFiles: string[] = glob.sync("./test/**/*.spec.js");
const pool = new Pool(cpuCount);
let jobCounter = 0;
const testStartTime = new Date();
const fileCount = testFiles.length;
let exitWithError = false;
let totalTestCount = 0;
let totalFailedTestCount = 0;

console.log(
    `Running tests: ${fileArrToString(testFiles)} with ${cpuCount} threads`);

testFiles.forEach(file => {
    pool.run("./test_thread")
        .send({files: [file]})
        .on("done",
            (testCount, failedTestCount) => {
              if (failedTestCount !== 0) {
github TypeScriptToLua / TypeScriptToLua / test / threaded_runner.ts View on Github external
function fileArrToString(fileArr: string[]): string {
    return fileArr.map(val => path.basename(val).replace(".spec.js", "")).join(", ");
}

function printTestStats(testCount: number, failedTestCount: number, header: string, footer: string): void {
    console.log("-----------------");
    console.log(header);
    console.log(`Total:  ${testCount}`);
    console.log(`Passed: ${testCount - failedTestCount}`);
    console.log(`Failed: ${failedTestCount}`);
    console.log(footer);
    console.log("-----------------");
}

config.set({
  basepath: {
    node: __dirname,
  }
});

let cpuCount = os.cpus().length + 1;
if ("TRAVIS" in process.env && "CI" in process.env) {
    // fixed thread count for CI
    cpuCount = 8;
}
const testFiles: string[] = glob.sync("./test/**/*.spec.js");
const pool = new Pool(cpuCount);
let jobCounter = 0;
const testStartTime = new Date();
const fileCount = testFiles.length;
let exitWithError = false;
github CampbellCrowley / SpikeyBot-Discord / src / music.js View on Github external
err.message);
      }
      broadcast.isLoading = false;
      skipSong(broadcast);
    });

    // Spawn thread for starting audio stream.
    const input = {
      song: broadcast.current.song,
      special: special,
      ytdlOpts: ytdlOpts,
    };
    if (broadcast.current.info) {
      input.song = broadcast.current.info.url;
    }
    broadcast.current.thread = spawn(startStream);
    broadcast.current.thread.send(input);
    broadcast.current.thread.on('progress', function(data) {
      if (data.ytdlinfo) {
        broadcast.current.oninfo(data.ytdlinfo);
        return;
      }
      if (data.data) data.data = Buffer.from(data.data);
      broadcast.current.readable.push(data.data);
    });
    broadcast.current.thread.on('done', function() {
      broadcast.current.thread.kill();
    });
    broadcast.current.thread.on('error', function(err) {
      self.error('Error in thread: ' + broadcast.current.song);
      console.log(err);
      if (broadcast.current.request) {
github higlass / higlass / app / scripts / data-fetchers / bam-fetcher-worker.js View on Github external
// console.log('positions:', positions);
  // console.log('colors:', colors);

  const objData = {
    rows,
    positionsBuffer,
    colorsBuffer,
    xScaleDomain: domain,
    xScaleRange: scaleRange,
  };

  // eslint-disable-next-line
  console.log('renderSegments took', performance.now() - t1);

  // Fritz: why are the two buffers returned twice?
  return Transfer(objData, [positionsBuffer, colorsBuffer]);
};
github higlass / higlass / app / scripts / data-fetchers / bam-fetcher-worker.js View on Github external
// eslint-disable-next-line
  console.log('renderSegments took', performance.now() - t1);

  // Fritz: why are the two buffers returned twice?
  return Transfer(objData, [positionsBuffer, colorsBuffer]);
};

const tileFunctions = {
  init,
  tilesetInfo,
  fetchTilesDebounced,
  tile,
  renderSegments,
};

expose(tileFunctions);
github satoshipay / solar / src / lib / stellar-ticker.ts View on Github external
export async function fetchAllAssets(testnet: boolean): Promise {
  const storageKey = testnet ? "known-assets:testnet" : "known-assets:mainnet"

  const cachedAssetsString = localStorage.getItem(storageKey)
  const timestamp = localStorage.getItem("known-assets:timestamp")

  if (cachedAssetsString && timestamp && +timestamp > Date.now() - 24 * 60 * 60 * 1000) {
    // use cached assets if they are not older than 24h
    return JSON.parse(cachedAssetsString)
  } else {
    const fetcher = await spawn(new Worker("../workers/fetch-worker.ts"))
    const allAssets = await fetcher.fetchAllAssets(testnet)
    await Thread.terminate(fetcher)

    localStorage.setItem(storageKey, JSON.stringify(allAssets))
    localStorage.setItem("known-assets:timestamp", Date.now().toString())

    return allAssets
  }
}
github VertigoRay / GDAXBot / main.js View on Github external
'use strict';

const fs = require('fs');
const Log = require('log');
const settings = require('config');
const spawn = require('threads').spawn;
const stats = require('stats-lite');
const sprintf = require('sprintf-js').sprintf;
const terminal = spawn('./lib/terminal.js');
const threads = require('threads');

if (settings.get('general.log')) {
	var log = new Log(settings.get('general.log_level'), fs.createWriteStream('GDAX.log'));
} else {
	let dev_null = (process.platform === 'win32') ? 'nul' : '/dev/null'
	var log = new Log(settings.get('general.log_level'), fs.createWriteStream(dev_null));
}

var terminal_data = {
	account: {
	// 	timestamp: new Date,
	// 	profile_id: 'e316cb9a-TEMP-FAKE-DATA-97829c1925de',
	// 	id: '343bb963-TEMP-FAKE-DATA-8b562d2f7a4e',
	// 	account: {
	// 		id: "a1b2c3d4",
github ChainSafe / lodestar / packages / lodestar / src / chain / factory / block / index.ts View on Github external
parentRoot: signingRoot(parentHeader, config.types.BeaconBlockHeader),
    // @ts-ignore
    signature: undefined,
    // @ts-ignore
    stateRoot: undefined,
    body: await assembleBody(config, opPool, eth1, merkleTree, currentState, randao),
  };

  const stat = await spawn(new Worker("../../../../../eth2.0-state-transition/src/stateTransition"))

  block.stateRoot = hashTreeRoot(
    await stat(config, currentState, block, false, false),
    config.types.BeaconState
  );

  await Thread.terminate(stat)
  return block;
}
github satoshipay / solar / src / lib / stellar-ticker.ts View on Github external
export async function fetchAllAssets(testnet: boolean): Promise {
  const storageKey = testnet ? "known-assets:testnet" : "known-assets:mainnet"

  const cachedAssetsString = localStorage.getItem(storageKey)
  const timestamp = localStorage.getItem("known-assets:timestamp")

  if (cachedAssetsString && timestamp && +timestamp > Date.now() - 24 * 60 * 60 * 1000) {
    // use cached assets if they are not older than 24h
    return JSON.parse(cachedAssetsString)
  } else {
    const fetcher = await spawn(new Worker("../workers/fetch-worker.ts"))
    const allAssets = await fetcher.fetchAllAssets(testnet)
    await Thread.terminate(fetcher)

    localStorage.setItem(storageKey, JSON.stringify(allAssets))
    localStorage.setItem("known-assets:timestamp", Date.now().toString())

    return allAssets
  }
}
github satoshipay / solar / src / lib / stellar-expert.ts View on Github external
export async function fetchWellknownAccounts(testnet: boolean): Promise {
  const cacheKey = testnet ? "known-accounts:testnet" : "known-accounts:mainnet"

  const cachedAccountsString = localStorage.getItem(cacheKey)
  const timestamp = localStorage.getItem("known-accounts:timestamp")

  if (cachedAccountsString && timestamp && +timestamp > Date.now() - 24 * 60 * 60 * 1000) {
    // use cached accounts if they are not older than 24h
    return JSON.parse(cachedAccountsString)
  } else {
    const fetcher = await spawn(new Worker("../workers/fetch-worker.ts"))
    const knownAccounts = await fetcher.fetchWellknownAccounts(testnet)
    await Thread.terminate(fetcher)

    localStorage.setItem(cacheKey, JSON.stringify(knownAccounts))
    localStorage.setItem("known-accounts:timestamp", Date.now().toString())
    return knownAccounts
  }
}