semaphore demo 并行 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

import 'dart:async';
import 'package:semaphore/semaphore.dart';
import 'dart:io';
import 'dart:convert';
import 'dart:math';

import "dart:math";

void main() async {
  int maxCount = 5;
  LocalSemaphore sm = LocalSemaphore(maxCount);
  List<Future> tasks = [];
  int end = 0;
  for (int i = 0; i < maxCount; i++) {
    tasks.add(eventLoop(sm, '$i', end));
  }
  await Future.wait(tasks);
}

Future eventLoop(LocalSemaphore sm, String key, int end) async {
  await sm.acquire();
  await doWork(key, 0, true, end);
  sm.release();
}

Future doWork(String key, int i, bool ok, int end) async {
  print('getting in thread: $key, bool is: $ok');
  bool b = ok;
  int a = end;
  if (b) {
    print('thread: $key, current: $i');
    await Future.delayed(Duration(seconds: 1));
    a += 1;
      if (a > 10) {
        print('change the bool.here thread: $key, and a is: $a');
        b = false;
      }else{
        b = true;
      }
      print('a is: $a');
    await doWork(key, i + 1, b, a);
  }
}

  

posted @ 2019-05-01 08:52  CrossPython  阅读(259)  评论(0编辑  收藏  举报