Giter VIP home page Giter VIP logo

Comments (5)

feikerwu avatar feikerwu commented on May 26, 2024 1

@suukii 如何保证两个线程交替执行呢?

自实现一个线程池,限制并发,通过message事件循环

from fe-interview.

suukii avatar suukii commented on May 26, 2024

Node

// thread1.js
const { Worker } = require('worker_threads');
const worker = new Worker('./thread2.js', {});

let code = 'A'.charCodeAt(0);
worker.on('message', msg => {
    process.stdout.write(msg);
    code++;
    code <= 'Z'.charCodeAt(0) && worker.postMessage(String.fromCharCode(code));
});

worker.postMessage(String.fromCharCode(code));

// thread2.js
const { parentPort } = require('worker_threads');

let count = 1;
parentPort.on('message', msg => {
    process.stdout.write(msg);
    count <= 26 && parentPort.postMessage(String(count));
    count++;
});

from fe-interview.

azl397985856 avatar azl397985856 commented on May 26, 2024

@suukii 如何保证两个线程交替执行呢?

from fe-interview.

suukii avatar suukii commented on May 26, 2024

好像这样可以吧,ps 为了让代码短一点 TestWorkerPool 的实现我就尽量写简单了。

不过为什么要让线程交替执行呢

const {
    Worker,
    isMainThread,
    parentPort,
    workerData,
} = require('worker_threads');

class TestWorkerPool {
    constructor(workerPath, numOfThreads) {
        this._workerPath = workerPath;
        this._queue = [];

        this._numOfThreads = numOfThreads;
        this._workersById = Array(numOfThreads);
        this._nextWorkerId = -1;
        this._activeWorker = null;

        this._init();
    }

    _init() {
        for (let i = 0; i < this._numOfThreads; i++) {
            this._workersById[i] = new Worker(this._workerPath, {
                workerData: { id: i },
            });
        }
    }

    _getNextWorkerId() {
        this._nextWorkerId++;
        if (this._nextWorkerId >= this._numOfThreads) this._nextWorkerId = 0;
        return this._nextWorkerId;
    }

    _runWorker(workerId, queueItem) {
        const worker = this._workersById[workerId];
        this._activeWorker = worker;

        const cleanUp = () => {
            worker.removeAllListeners('message');
            worker.removeAllListeners('error');
            this._activeWorker = null;

            if (this._queue.length)
                this._runWorker(this._getNextWorkerId(), this._queue.shift());
        };

        worker.once('message', cleanUp);
        worker.once('error', cleanUp);

        worker.postMessage(queueItem);
    }

    run(data) {
        const queueItem = data;
        if (this._activeWorker) {
            this._queue.push(queueItem);
            return null;
        }
        this._runWorker(this._getNextWorkerId(), queueItem);
    }
}

if (isMainThread) {
    const pool = new TestWorkerPool('./test.js', 2);
    for (let i = 1; i <= 26; i++) {
        pool.run(String.fromCharCode(i + 64));
        pool.run(String(i));
    }
} else {
    parentPort.on('message', data => {
        console.log(`worker${workerData.id}: ${data}`);
        parentPort.postMessage('done');
    });
}

// worker0: A;
// worker1: 1;
// worker0: B;
// worker1: 2;
// worker0: C;
// worker1: 3;

from fe-interview.

stale avatar stale commented on May 26, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

from fe-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.