我有一个生成哈希密码的应用程序并生成它需要时间。我认为为了提高性能,我会让哈希密码生成器在单独的核心中工作。我的计算机支持3个核心处理器,我认为使用dart:isolate来计算其他处理器核心中的散列密码是个好主意。
我试过以下:
import 'dart:isolate';
import 'package:dbcrypt/dbcrypt.dart';
main() {
ReceivePort receivePort = new ReceivePort();
var receivePortPw = new ReceivePort();
receivePortPw.listen((msg) {
print(msg);
});
Isolate.spawn(ReturnHashedPassword, receivePortPw.sendPort);
print('Print1 -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
print('Print2 -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
}
void ReturnHashedPassword(SendPort sendPort)
{
ReceivePort receivePort = new ReceivePort();
sendPort.send('Isolate -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
}
作为输出我有
Print1 -> $2a$10$XggGPuIyLP2GLon2eKtW2.kG5QwK4fkiIDFa8hkgDPdy1h1AAC6LO
Print2 -> $2a$10$zK..L6Hi0NkeRbkm2/v6H.5s25QQSjwRszI83.i3CzFZlb7pFCW6G
Isolate -> $2a$10$DM/.25em/3amvGNu2G6Wl.SQQ2ECGSE6DUwPc56tvdoMGw9ZBja36
似乎是,它不兼容并发。我预计,隔离将是第一个或第二个不是最后一个。我有什么不对吗?
答案 0 :(得分:5)
您的代码同时工作。将print()添加到Isolate的函数时,如下所示:
void ReturnHashedPassword(SendPort sendPort)
{
print('ok');
ReceivePort receivePort = new ReceivePort();
sendPort.send('Isolate -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
print('done');
}
输出将是:
ok
done
Print1 -> $2a$10$p..GSYxybtjmbrhKe.xu1.IfEUihBxXPL9DYCLHqx72yKHsZB0e1e
Print2 -> $2a$10$eA.2bNvakH6uBFjiWNwua.jDUBhgYPsMP2PyOpsGd84GCx.spaAS.
Isolate -> $2a$10$.sBmleeuV5U.NaSGOE6ON.kxQ7Cnq6yj8IXRBgCZgx8TGmcBZT7Ny
我猜dart有一些内置的资源分配算法,可以为进程提供stdout,以避免出现奇怪的打印。
当你改变你的代码时:
import 'dart:isolate';
import 'package:dbcrypt/dbcrypt.dart';
import 'dart:async';
main() {
//ReceivePort receivePort = new ReceivePort();
var receivePortPw = new ReceivePort();
receivePortPw.listen((msg) {
print(msg);
});
Future<Isolate> f = Isolate.spawn(ReturnHashedPassword, receivePortPw.sendPort);
f.then((Isolate i) {
print('Print1 -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
print('Print2 -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
});
}
void ReturnHashedPassword(SendPort sendPort)
{
print('ok');
ReceivePort receivePort = new ReceivePort();
sendPort.send('Isolate -> ' + new DBCrypt().hashpw('Password', new DBCrypt().gensalt()));
print('done');
}
输出结果为:
ok
Print1 -> $2a$10$zABOnUhKUn.GqERW2Euu7.HpzNizwTDyDbSSLe0b1XL6o9jEo/4dm
done
Print2 -> $2a$10$SE.eczx2i1o2dfey.NpSI.gZXhJU9KDWPAp1UtOFBjUI/ltjppwy2
Isolate -> $2a$10$s.B.0dnGQ0KO1za..I5uL.U1ARKLUK/Jtv/.O8BjP7gQroidvesEC
你可以看到它正在并发工作。
问候,罗伯特