isolate的理解
isolate原型
external static Future<Isolate> spawn<T>(
void entryPoint(T message), T message,
{bool paused = false,
bool errorsAreFatal = true,
SendPort? onExit,
SendPort? one rror,
@Since("2.3") String? debugName});
isolate功能和名字基本一直,能够调用另外的CPU内核
进程与线程是操作系统的概念,进程间的内存空间是隔离,是相互看不见,摸不着,访问不了的。而一个进程内的多个线程,共用同一个地址空间,也即多线程之间内存是完全共享的
dart的isolate就是isolate,是自己语言本身的一个特点
如下是isolate使用其下面的spawn来创建一个新的isoalte,isolate有着独立的堆栈(可以这样理解:如果使用isolate外面的变量isolate会创建一个新的变量,并且将值进行赋值),我们一般只能是从isolate里面向外传出消息,isolate规定如果message传递的是port的话,只能是sendport,也就是只能向外发发送消息,那怎么向里面发送消息呢,也就在里面发送一个sendPort给外面就行了经过测试,在里面向外发送receivePort会报错
void main() async {
//1.创建管道
ReceivePort receivePort1 = ReceivePort();
//2.创建Isolate
Isolate.spawn<SendPort>((SendPort send) async {
ReceivePort receivePort2 = ReceivePort();
receivePort2.listen((message) {
print("isolate->${message}");
});
send.send({"sendPort": receivePort2.sendPort});
}, receivePort1.sendPort);
//3.监听管道
receivePort1.listen((message) {
Map<String, dynamic> map;
map = message as Map<String, dynamic>;
if(map["sendPort"] != null){
print("receive sendPort");
int a = 0;
SendPort sendPort = map["sendPort"];
while(true){
sendPort.send(a++);
sleep(const Duration(seconds: 1));
}
}else{
print(map["data"]);
}
});
}
什么是并行
The underlying idea in parallel computing is that the computational problem can be split into smaller subtasks. Multiple subtasks can then be executed simultaneously by multiple processing units. In modern CPUs, the single execution unit is typically a CPU core.
因此isolate是实现并行的一种体现