gpt4 book ai didi

multithreading - Flutter Dart : How can we achieve multithreading like python or java in dart

转载 作者:行者123 更新时间:2023-12-03 03:23:27 31 4
gpt4 key购买 nike

我想实现线程A 线程B 并行运行并共享全局变量。

下面是用python编写的代码。我想在中执行相同操作Dart (我不想使用future等待,因为它正在等待其他线程完成或必须等待。)

大小写变量:

val 
ai ( a increment )
ad ( a decrement )
af ( a fail )
bi ( b increment )
bd ( b decrement )
bf ( b fail ) // when unable to get log

我有两个函数 A() B()和全局变量val。
这两个函数都随机增加或减少全局变量val。
并基于此我正在计算错误并打印到控制台(用pr函数编写)
O.val (Original val received at time of executing)
C.val (Calculated val)
err= ai - ad + bi - bd - val


_/+ O.val C.val ai ad ai-ad bi bd bi-ad err

A- | 0 -1 | 0 1 -1 | 0 0 0 | 0
B+ | -1 0 | 0 1 -1 | 1 0 1 | 0
A- | 0 -1 | 0 2 -2 | 1 0 1 | 0
B+ | -1 0 | 0 2 -2 | 2 0 2 | 0
A- | 0 -1 | 0 3 -3 | 2 0 2 | 0
B- | -1 -2 | 0 3 -3 | 2 1 1 | 0


Python方面:
##############
# Python Code
# ############

import thread;
import time;

def lhrand(lo, hi): import random; return lo + int (random.random() * (hi - lo));

mutex= thread.allocate_lock();
val= 0;
ai= ad= af= 0;
bi= bd= bf= 0;

def pr(id, sign, _val):
global val, ai, ad, af, bi, bd, bf;
return "%s%s | %5d %5d | %5d %5d %5d | %5d %5d %5d | %4d" % (id, sign, _val, val, ai, ad, af, bi, bd, bf, ai - ad + bi - bd - val);

def A(id):
global val, ai, ad;
for j in range(0, 10000):
r= lhrand(0, 2);
s= "-+"[r];
w= [-1, 1][r];
line= None;
if mutex:
if mutex.acquire():
o= val;
if r == 0: ad+= 1; else: ai+= 1;
val= val + w;
pr(id, "-" if r == 0 else "+", o);
mutex.release();
line= pr(id, s, o);
print("%s over" % id);
return 0;


def B(id):
global val, bi, bd;
for j in range(0, 10000):
if mutex and mutex.acquire():
r= lhrand(0, 2);
o= x= val;
if r == 0: bd+= 1;
if r == 1: bi+= 1;
x= x - 1 if r == 0 else x + 1;
val= x;
pr(id, "-" if r == 0 else "+", o);
mutex.release();
print("%s over" % id);
return 0;

if __name__ == "__main__":
x= thread.start_new_thread(A, ("A",))
y= thread.start_new_thread(B, ("B",))
time.sleep(5.0);
pr("X", ".", val);

exit(0);


Dart 面:
/////////////
// Dart Code
/////////////

import "dart:async";
import "dart:math";
import "package:threading/threading.dart";
import "package:sprintf/sprintf.dart";

int val= 0;
int ai= 0, ad= 0, bi=0, bd= 0;
int num= 10000;

Lock _lock = new Lock();

var isLockEnable= true;

Random random= new Random();
int lhrand(lo, hi)
{
return lo + random.nextInt(hi - lo);
}

int pr(id, sign, _val)
{
var s= sprintf("%s%s | %5d %5d | %5d %5d %5d | %5d %5d %5d | %4d", [id, sign, _val, val, ai, ad, ai - ad, bi, bd, bi - bd, ai - ad + bi - bd - val]);
print(s);
return 0;
}
Future A() async
{
int r, o, x;
var id= "A";
for(var j in Iterable<int>.generate(num).toList())
{
try
{
if(isLockEnable)
{
await _lock.acquire();
}
o= await Future((){ return val; });
x= val;
r= lhrand(0, 2);
x= val;
if(r == 0) { ad++; }
if(r == 1) { ai++; }
x= (r == 0) ? x - 1 : x + 1;
val= x;
pr(id, (r == 0) ? "-" : "+", o);
if(isLockEnable)
{
await _lock.release();
}
}
catch(e)
{
print("A failed to get lock.");
}
}
print("$id over");
}
Future B() async
{
int r, o, x;
var id= "B";
for(var j in Iterable<int>.generate(num).toList())
{
try
{
if(isLockEnable)
{
await _lock.acquire();
}
o= await Future((){ return val; });
r= lhrand(0, 2);
x= val;
if(r == 0) { bd++; }
if(r == 1) { bi++; }
x= (r == 0) ? x - 1 : x + 1;
val= x;
pr(id, (r == 0) ? "-" : "+", o);
if(isLockEnable)
{
await _lock.release();
}
}
catch(e)
{
print("B failed to get lock.");
}
}
print("$id over");
}
Future main() async
{
var AT= new Thread(A);
print("AT : " + AT.hashCode.toString());
var BT= new Thread(B);
print("BT : " + BT.hashCode.toString());
AT.start();
BT.start();
return 0;
}

最佳答案

Dart/Flutter是单线程的,无法共享全局变量。由于每个隔离区都有自己的内存,空间和所有内容。为了使其像多线程一样工作,您必须使用隔离,并且通过向彼此发送消息来通过端口使用通信。如果您不想使用Future,则可以使用隔离。


  • https://medium.com/flutter-community/flutter-threading-5c3a7b0c065f
  • https://www.tutorialspoint.com/dart_programming/dart_programming_concurrency.htm
  • https://pub.dev/packages/threading
  • 关于multithreading - Flutter Dart : How can we achieve multithreading like python or java in dart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525666/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com