-1

may i ask how to multithreading some functions in dart for example i have 16 Future functions i want first to execute this function in the first thread

await GetRoot(); //Future<void>

then after the first thread end i want to execute theses functions in the second thread -togather at the same time-

 await GetLocalRadio();//Future<void>
  await GetMusic();//Future<void>
  await GetTalk();//Future<void>
  await GetSports();//Future<void>
  await GetByLocation();//Future<void>
  await GetByLanguage();//Future<void>
  await GetPodcasts();//Future<void>

then after the second thread is finished , i want to execute these threads togather at the same time in the next thread

 await GetPodcasts2();//Future<void>
  await GetByLocation2();//Future<void>

then when the second thread end i want when the third functions is finished to execute these functions togather at the same time in a new thread

  await FillPdcasts();//Future<void>
  await FillLocalRadio();//Future<void>
  await FillMusic();//Future<void>
  await FillTalk();//Future<void>
  await FillSports();//Future<void>
  await FillByLocation();//Future<void>

here is a simple of the content of all methods that i have

 Future<void> FillByLocation()
  async {
    for (var entry in xByLocation2) {
        final responseFinalByLocation2 = await http.Client().get(entry.split('^')[1], headers: {'Content-Type': 'application/json; charset=utf-8'});
        try{
          final FinalByLocation2final = allInfosFromJson(utf8.decode(responseFinalByLocation2.bodyBytes));
          for (int i = 0; i < FinalByLocation2final.body.length; i++) {
            for (int j = 0; j < FinalByLocation2final.body[i].children.length; j++) {
              if(FinalByLocation2final.body[i].children[j].text != null && FinalByLocation2final.body[i].children[j].image != null)
              {
                if(!xListFinalAllInfos.contains(FinalByLocation2final.body[i].children[j].text + "^" + FinalByLocation2final.body[i].children[j].subtext + "^" + FinalByLocation2final.body[i].children[j].nowPlayingId + "^" + FinalByLocation2final.body[i].children[j].currentTrack+ "^" + FinalByLocation2final.body[i].children[j].url+ "^" + FinalByLocation2final.body[i].children[j].image))
                  {
                    setState(() {
                      xListFinalAllInfos.add(FinalByLocation2final.body[i].children[j].text + "^" + FinalByLocation2final.body[i].children[j].subtext + "^" + FinalByLocation2final.body[i].children[j].nowPlayingId + "^" + FinalByLocation2final.body[i].children[j].currentTrack+ "^" + FinalByLocation2final.body[i].children[j].url+ "^" + FinalByLocation2final.body[i].children[j].image);
                      // ListFinalAllInfos.putIfAbsent(
                      //     FinalByLocation2final.body[i].children[j].text, () =>
                      // FinalByLocation2final.body[i].children[j].image );
                    });
                  }
              }
            }
          }
        }catch(e){}
      }
  }

Because when I execute all the functions and await all of them, then this will take about 30 seconds. This is a lot of time, so I need to make the time less than 30 seconds.

test firma
  • 171
  • 1
  • 1
  • 6
  • It's impossible for us to tell if these functions can even be run in isolates without showing us the contents of these functions. Are you already running these functions in isolates? – Christopher Moore Oct 23 '20 at 12:02
  • thanks for your help. no it's not impossible cause i mentioned that these methods are Future so i think it's not possible to run in isolates cause their types are Future of void, isn't ? – test firma Oct 23 '20 at 12:05
  • Are you saying these functions cannot be run in isolates? You cannot get close to multithreading without isolates. – Christopher Moore Oct 23 '20 at 12:06
  • sorry i just saw your comment and repaid, i will update the thread and write the content of one of the methods for example cause they are all the same – test firma Oct 23 '20 at 12:07
  • It's definitely not possible to run this method in an isolate in its current state. What's the motivation to do multithreading? What's wrong with just asynchrony? – Christopher Moore Oct 23 '20 at 12:09
  • i think yes, these functions cannot running in isolate , but there is a package that call multithread , so can i use it instead of isolate , isn't ? i added a sample for the functions that i have, they are all the same and doing the same work, thanks again for your help – test firma Oct 23 '20 at 12:10
  • I see no such package. Dart is not a multithreaded language. Isolates are as close are you're going to get. If you can't use isolates, then this simply can't be done. Why is multithreading so important? What's wrong with just asynchrony? – Christopher Moore Oct 23 '20 at 12:12
  • here is that package that i ment https://pub.dev/packages/threading and the wrong is that as i mentioned is the time for executing all the 16 methods and awaiting them one by one, and there is no need to wait them one by one, cause the first method collects the necessary datat to let the next 7 methods to be able to work togather, so if i awaited the next 7 methods one by one this will take more time than if i executed them togather at the same time, this is my problem, and the rest of the functions have the same time issue. – test firma Oct 23 '20 at 12:17
  • Please see my answer. Your method of implementing asynchrony is very flawed. There is no need or benefit from multithreading. – Christopher Moore Oct 23 '20 at 12:20
  • after awaiting and executing this method GetRoot() then the next 7 methods can be able to work togather cause they need just the data that GetRoot() Provided, and when the next 7 methods has been executed then the next two methods can be able to work togather at the same time cause the last 7 methods provided that necessary data to let the next methods working fine, and when these two methods executed then the next and last 6 methodscan be able to work togather cause the last two methods provided the necessary data for them, so i need to save time instead awaiting them one by one – test firma Oct 23 '20 at 12:22

1 Answers1

0

Multithreading is not an option here. Just stick with asynchrony.

All of your awaits are making your code much slower. You're forcing the previous function to finish before the next function can even start. Call them all at the same time and use Future.wait.

await GetRoot();

List<Future<void>> toWait = [];
toWait.add(GetLocalRadio());
toWait.add(GetMusic());
...

await Future.wait(toWait);
toWait.clear();

toWait.add(GetPodcasts2());
toWait.add(GetByLocation2());

await Future.wait(toWait);
toWait.clear();

toWait.add(FillPdcasts());
toWait.add(FillLocalRadio());
...

await Future.wait(toWait);
toWait.clear();

Additionally, the work you're doing within these function is also implemented inefficiently. You're waiting for each http call to finish before processing the data from the call and starting the next one. This can be made more efficient.

The following code uses .then to register callbacks for each of the network calls, stores the futures to a list, and uses Future.wait at the very end to ensure they're all completed before the wrapper function returns.

 Future<void> FillByLocation()
  async {
    List<Future<void>> toWait = [];
    for (var entry in xByLocation2) {
        toWait.add(http.Client().get(entry.split('^')[1], headers: {'Content-Type': 'application/json; charset=utf-8'}).then((responseFinalByLocation2){
        try{
          final FinalByLocation2final = allInfosFromJson(utf8.decode(responseFinalByLocation2.bodyBytes));
          for (int i = 0; i < FinalByLocation2final.body.length; i++) {
            for (int j = 0; j < FinalByLocation2final.body[i].children.length; j++) {
              if(FinalByLocation2final.body[i].children[j].text != null && FinalByLocation2final.body[i].children[j].image != null)
              {
                if(!xListFinalAllInfos.contains(FinalByLocation2final.body[i].children[j].text + "^" + FinalByLocation2final.body[i].children[j].subtext + "^" + FinalByLocation2final.body[i].children[j].nowPlayingId + "^" + FinalByLocation2final.body[i].children[j].currentTrack+ "^" + FinalByLocation2final.body[i].children[j].url+ "^" + FinalByLocation2final.body[i].children[j].image))
                  {
                    setState(() {
                      xListFinalAllInfos.add(FinalByLocation2final.body[i].children[j].text + "^" + FinalByLocation2final.body[i].children[j].subtext + "^" + FinalByLocation2final.body[i].children[j].nowPlayingId + "^" + FinalByLocation2final.body[i].children[j].currentTrack+ "^" + FinalByLocation2final.body[i].children[j].url+ "^" + FinalByLocation2final.body[i].children[j].image);
                      // ListFinalAllInfos.putIfAbsent(
                      //     FinalByLocation2final.body[i].children[j].text, () =>
                      // FinalByLocation2final.body[i].children[j].image );
                    });
                  }
              }
            }
          }
        }catch(e){}
        }));
      }
    await Future.wait(toWait);
  }
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52