我正在编写一些加密代码,这些代码将对信息进行加密,解密,签名和验证。我想让每个函数都在不同的线程上运行。我试图在网上找到答案,但是找不到关于多线程的参考文章来回答我的问题。是否有任何文章可以针对我的情况向我清楚地解释多线程?
我的代码:
const cluster = require('cluster'); const numCPUs = require('os').cpus().length; let events = require('events'); const crypto = require('crypto'); const readline = require('readline'); const sign = crypto.createSign('SHA256'); const NodeRSA = require('node-rsa'); const { MessageChannel } = require('worker_threads'); const {Worker, isMainThread, parentPort, workerData} = require('worker_threads'); let eventEmitter = new events.EventEmitter(); let key = new NodeRSA({}); key.generateKeyPair(2048); console.log(key.isPublic(true));
function signing(message) {
return key.sign(message, 'base64'); }
function verification(signature, message) {
return key.verify(message, signature,"ascii","base64"); }
/*let rl = readline.createInterface({
input: process.stdin,
output: process.stdout });
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close(); });*/ // for reading user input later let message1 = "Hi, this is just the first test"; console.log(message1); let temp = "random";
let listener1 = function() {
console.log('listener1 executed.');
temp = key.encrypt(message1, "base64");
console.log(temp); }
let listener2 = function() {
console.log('listener2 executed.');
temp = key.decrypt(temp, "ascii");
console.log(temp);
}
let listener3 = function() {
console.log('listener3 executed.');
temp = signing(temp,"base64");
console.log(temp); }
let listener4 = function() {
console.log('listener4 executed.');
console.log(temp);
temp = verification(temp, message1);
console.log(temp); }
eventEmitter.addListener('encrypt', listener1);
eventEmitter.on('decrypt', listener2); eventEmitter.on('sign', listener3); eventEmitter.on('validate', listener4); let eventListeners
= require('events').EventEmitter.listenerCount(eventEmitter, 'decrypt'); console.log(eventListeners + " Listner(s) listening to decrypt event");
// Fire the connection event eventEmitter.emit('encrypt');
// Fire the connection event eventEmitter.emit('decrypt');
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter, 'decrypt'); console.log(eventListeners + " Listener(s) listening to encrypt event");
eventEmitter.emit("sign"); eventListeners = require('events').EventEmitter.listenerCount(eventEmitter, 'sign'); console.log(eventListeners + " Listener(s) listening to signing event");
eventEmitter.emit("validate"); eventListeners = require('events').EventEmitter.listenerCount(eventEmitter, 'validate'); console.log(eventListeners + " Listener(s) listening to validation event");
console.log("Program Ended.");