3

我有一个生成散列密码的应用程序,生成它需要时间。我认为为了提高性能,我会让散列密码生成器在单独的核心中工作。我的计算机支持 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

似乎是,它不能并发工作。我预计,隔离将是第一名或第二名,而不是最后一名。我在这里做错了什么?

4

1 回答 1

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 有一些内置的资源分配算法,可以为进程提供标准输出以避免奇怪的打印。

当您像这样更改代码时:

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

您可以看到它正在并发工作。

问候,罗伯特

于 2014-06-27T07:18:47.793 回答