channel.py 27.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=doc-string-missing
D
dongdaxiang 已提交
15 16 17 18 19 20 21 22 23 24
import threading
import multiprocessing
import multiprocessing.queues
import sys
if sys.version_info.major == 2:
    import Queue
elif sys.version_info.major == 3:
    import queue as Queue
else:
    raise Exception("Error Python version")
25 26 27 28
import numpy as np
import logging
import enum
import copy
D
dongdaxiang 已提交
29

W
wangjiawei04 已提交
30
_LOGGER = logging.getLogger()
B
barrierye 已提交
31

D
dongdaxiang 已提交
32 33 34 35 36 37 38

class ChannelDataEcode(enum.Enum):
    OK = 0
    TIMEOUT = 1
    NOT_IMPLEMENTED = 2
    TYPE_ERROR = 3
    RPC_PACKAGE_ERROR = 4
B
barrierye 已提交
39 40
    CLIENT_ERROR = 5
    UNKNOW = 6
D
dongdaxiang 已提交
41 42 43 44 45 46 47 48


class ChannelDataType(enum.Enum):
    DICT = 0
    CHANNEL_NPDATA = 1
    ERROR = 2


49 50 51 52
class ChannelData(object):
    def __init__(self,
                 datatype=None,
                 npdata=None,
B
barrierye 已提交
53
                 dictdata=None,
54 55 56 57 58 59
                 data_id=None,
                 ecode=None,
                 error_info=None):
        '''
        There are several ways to use it:
        
B
barrierye 已提交
60 61 62
        1. ChannelData(ChannelDataType.CHANNEL_NPDATA.value, npdata, data_id)
        2. ChannelData(ChannelDataType.DICT.value, dictdata, data_id)
        3. ChannelData(ecode, error_info, data_id)
63 64 65 66 67 68 69 70 71

        Protobufs are not pickle-able:
        https://stackoverflow.com/questions/55344376/how-to-import-protobuf-module
        '''
        if ecode is not None:
            if data_id is None or error_info is None:
                raise ValueError("data_id and error_info cannot be None")
            datatype = ChannelDataType.ERROR.value
        else:
B
barrierye 已提交
72 73
            if datatype == ChannelDataType.CHANNEL_NPDATA.value:
                ecode, error_info = ChannelData.check_npdata(npdata)
74
                if ecode != ChannelDataEcode.OK.value:
B
barrierye 已提交
75
                    datatype = ChannelDataType.ERROR.value
B
barrierye 已提交
76
                    _LOGGER.error(error_info)
B
barrierye 已提交
77 78 79 80
            elif datatype == ChannelDataType.DICT.value:
                ecode, error_info = ChannelData.check_dictdata(dictdata)
                if ecode != ChannelDataEcode.OK.value:
                    datatype = ChannelDataType.ERROR.value
B
barrierye 已提交
81
                    _LOGGER.error(error_info)
82 83 84
            else:
                raise ValueError("datatype not match")
        self.datatype = datatype
B
barrierye 已提交
85 86
        self.npdata = npdata
        self.dictdata = dictdata
87 88 89 90
        self.id = data_id
        self.ecode = ecode
        self.error_info = error_info

B
barrierye 已提交
91 92 93 94
    @staticmethod
    def check_dictdata(dictdata):
        ecode = ChannelDataEcode.OK.value
        error_info = None
B
barrierye 已提交
95 96 97 98 99 100 101 102 103 104
        if isinstance(dictdata, list):
            # batch data
            for sample in dictdata:
                if not isinstance(sample, dict):
                    ecode = ChannelDataEcode.TYPE_ERROR.value
                    error_info = "the value of data must " \
                            "be dict, but get {}.".format(type(sample))
                    break
        elif not isinstance(dictdata, dict):
            # batch size = 1
B
barrierye 已提交
105
            ecode = ChannelDataEcode.TYPE_ERROR.value
B
barrierye 已提交
106 107
            error_info = "the value of data must " \
                        "be dict, but get {}.".format(type(dictdata))
B
barrierye 已提交
108
        return ecode, error_info
B
barrierye 已提交
109

B
barrierye 已提交
110 111
    @staticmethod
    def check_npdata(npdata):
112 113
        ecode = ChannelDataEcode.OK.value
        error_info = None
W
wangjiawei04 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        if isinstance(npdata, list):
            # batch data
            for sample in npdata:
                if not isinstance(sample, dict):
                    ecode = ChannelDataEcode.TYPE_ERROR.value
                    error_info = "the value of data must " \
                            "be dict, but get {}.".format(type(sample))
                    break
                for _, value in sample.items():
                    if not isinstance(value, np.ndarray):
                        ecode = ChannelDataEcode.TYPE_ERROR.value
                        error_info = "the value of data must " \
                                "be np.ndarray, but get {}.".format(type(value))
                        return ecode, error_info
        elif isinstance(npdata, dict):
            # batch_size = 1
            for _, value in npdata.items():
                if not isinstance(value, np.ndarray):
                    ecode = ChannelDataEcode.TYPE_ERROR.value
                    error_info = "the value of data must " \
                            "be np.ndarray, but get {}.".format(type(value))
                    break
        else:
            ecode = ChannelDataEcode.TYPE_ERROR.value
            error_info = "the value of data must " \
                    "be dict, but get {}.".format(type(npdata))
140 141 142 143
        return ecode, error_info

    def parse(self):
        feed = None
B
barrierye 已提交
144 145
        if self.datatype == ChannelDataType.CHANNEL_NPDATA.value:
            # return narray
146
            feed = self.npdata
B
barrierye 已提交
147 148 149
        elif self.datatype == ChannelDataType.DICT.value:
            # return dict
            feed = self.dictdata
150 151 152 153 154 155 156 157 158
        else:
            raise TypeError("Error type({}) in datatype.".format(self.datatype))
        return feed

    def __str__(self):
        return "type[{}], ecode[{}], id[{}]".format(
            ChannelDataType(self.datatype).name, self.ecode, self.id)


B
barrierye 已提交
159
class ProcessChannel(object):
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    """ 
    (Process version) The channel used for communication between Ops.

    1. Support multiple different Op feed data (multiple producer)
        Different types of data will be packaged through the data ID
    2. Support multiple different Op fetch data (multiple consumer)
        Only when all types of Ops get the data of the same ID,
        the data will be poped; The Op of the same type will not
        get the data of the same ID.
    3. (TODO) Timeout and BatchSize are not fully supported.

    Note:
    1. The ID of the data in the channel must be different.
    2. The function add_producer() and add_consumer() are not thread safe,
       and can only be called during initialization.
B
barrierye 已提交
175 176 177 178 179 180 181 182 183 184 185

    There are two buffers and one queue in Channel:

        op_A \                                           / op_D
        op_B - a. input_buf -> b. queue -> c. output_buf - op_E
        op_C /                                           \ op_F
    
    a. In input_buf, the input of multiple predecessor Ops is packed by data ID.
    b. The packed data will be stored in queue.
    c. In order to support multiple successor Ops to retrieve data, output_buf
        maintains the data obtained from queue.
186 187 188
    """

    def __init__(self, manager, name=None, maxsize=0, timeout=None):
B
barrierye 已提交
189 190 191 192 193 194 195
        # For queue multiprocess: after putting an object on 
        # an empty queue there may be an infinitessimal delay
        # before the queue's :meth:`~Queue.empty`
        # see more:
        # - https://bugs.python.org/issue18277
        # - https://hg.python.org/cpython/rev/860fc6a2bd21
        self._que = manager.Queue(maxsize=maxsize)
196 197 198 199 200 201 202 203
        self._maxsize = maxsize
        self._timeout = timeout
        self.name = name
        self._stop = False

        self._cv = multiprocessing.Condition()

        self._producers = []
B
barrierye 已提交
204
        self._pushed_producer_count = manager.dict()  # {data_id: count}
B
barrierye 已提交
205
        self._input_buf = manager.dict()  # {data_id: {op_name: data}}
206

207
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
208 209 210 211
        self._consumer_cursors = manager.dict()  # {op_name: cursor}
        self._cursor_count = manager.dict()  # {cursor: count}
        self._base_cursor = manager.Value('i', 0)
        self._output_buf = manager.list()
212 213 214 215 216

    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
217
        return self._consumer_cursors.keys()
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

    def _log(self, info_str):
        return "[{}] {}".format(self.name, info_str)

    def debug(self):
        return self._log("p: {}, c: {}".format(self.get_producers(),
                                               self.get_consumers()))

    def add_producer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
        if op_name in self._producers:
            raise ValueError(
                self._log("producer({}) is already in channel".format(op_name)))
        self._producers.append(op_name)

    def add_consumer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
B
barrierye 已提交
235
        if op_name in self._consumer_cursors:
236 237
            raise ValueError(
                self._log("consumer({}) is already in channel".format(op_name)))
B
barrierye 已提交
238
        self._consumer_cursors[op_name] = 0
239

B
barrierye 已提交
240 241 242
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
243 244

    def push(self, channeldata, op_name=None):
B
barrierye 已提交
245
        _LOGGER.debug(
246 247 248 249 250 251 252 253 254 255 256
            self._log("{} try to push data: {}".format(op_name,
                                                       channeldata.__str__())))
        if len(self._producers) == 0:
            raise Exception(
                self._log(
                    "expected number of producers to be greater than 0, but the it is 0."
                ))
        elif len(self._producers) == 1:
            with self._cv:
                while self._stop is False:
                    try:
B
barrierye 已提交
257
                        self._que.put({op_name: channeldata}, timeout=0)
258 259 260
                        break
                    except Queue.Full:
                        self._cv.wait()
B
barrierye 已提交
261
                _LOGGER.debug(
262
                    self._log("{} channel size: {}".format(op_name,
B
barrierye 已提交
263
                                                           self._que.qsize())))
264
                self._cv.notify_all()
B
barrierye 已提交
265 266
                _LOGGER.debug(self._log("{} notify all".format(op_name)))
            _LOGGER.debug(self._log("{} push data succ!".format(op_name)))
267 268 269 270 271 272 273 274 275 276
            return True
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple producers, so op_name cannot be None."))

        producer_num = len(self._producers)
        data_id = channeldata.id
        put_data = None
        with self._cv:
B
barrierye 已提交
277
            _LOGGER.debug(self._log("{} get lock".format(op_name)))
B
barrierye 已提交
278 279
            if data_id not in self._input_buf:
                self._input_buf[data_id] = {
280 281 282
                    name: None
                    for name in self._producers
                }
B
barrierye 已提交
283
                self._pushed_producer_count[data_id] = 0
284
            # see: https://docs.python.org/3.6/library/multiprocessing.html?highlight=multiprocess#proxy-objects
B
barrierye 已提交
285 286 287 288 289
            # self._input_buf[data_id][op_name] = channeldata
            tmp_input_buf = self._input_buf[data_id]
            tmp_input_buf[op_name] = channeldata
            self._input_buf[data_id] = tmp_input_buf

B
barrierye 已提交
290
            if self._pushed_producer_count[data_id] + 1 == producer_num:
B
barrierye 已提交
291 292
                put_data = self._input_buf[data_id]
                self._input_buf.pop(data_id)
B
barrierye 已提交
293
                self._pushed_producer_count.pop(data_id)
294
            else:
B
barrierye 已提交
295
                self._pushed_producer_count[data_id] += 1
296 297

            if put_data is None:
B
barrierye 已提交
298
                _LOGGER.debug(
299 300 301 302 303
                    self._log("{} push data succ, but not push to queue.".
                              format(op_name)))
            else:
                while self._stop is False:
                    try:
B
barrierye 已提交
304
                        _LOGGER.debug(
305 306
                            self._log("{} push data succ: {}".format(
                                op_name, put_data.__str__())))
B
barrierye 已提交
307
                        self._que.put(put_data, timeout=0)
308 309 310 311
                        break
                    except Queue.Empty:
                        self._cv.wait()

B
barrierye 已提交
312
                _LOGGER.debug(
313 314 315 316 317
                    self._log("multi | {} push data succ!".format(op_name)))
            self._cv.notify_all()
        return True

    def front(self, op_name=None):
B
barrierye 已提交
318
        _LOGGER.debug(self._log("{} try to get data...".format(op_name)))
B
barrierye 已提交
319
        if len(self._consumer_cursors) == 0:
320 321 322 323
            raise Exception(
                self._log(
                    "expected number of consumers to be greater than 0, but the it is 0."
                ))
B
barrierye 已提交
324
        elif len(self._consumer_cursors) == 1:
325 326 327 328
            resp = None
            with self._cv:
                while self._stop is False and resp is None:
                    try:
B
barrierye 已提交
329
                        _LOGGER.debug(
330
                            self._log("{} try to get(with channel empty: {})".
B
barrierye 已提交
331
                                      format(op_name, self._que.empty())))
332 333 334 335 336 337
                        # For queue multiprocess: after putting an object on 
                        # an empty queue there may be an infinitessimal delay
                        # before the queue's :meth:`~Queue.empty`
                        # see more:
                        # - https://bugs.python.org/issue18277
                        # - https://hg.python.org/cpython/rev/860fc6a2bd21
B
barrierye 已提交
338
                        resp = self._que.get(timeout=1e-3)
339 340
                        break
                    except Queue.Empty:
B
barrierye 已提交
341
                        _LOGGER.debug(
342 343
                            self._log(
                                "{} wait for empty queue(with channel empty: {})".
B
barrierye 已提交
344
                                format(op_name, self._que.empty())))
345
                        self._cv.wait()
B
barrierye 已提交
346
            _LOGGER.debug(
347 348 349 350 351 352 353 354
                self._log("{} get data succ: {}".format(op_name, resp.__str__(
                ))))
            return resp
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple consumers, so op_name cannot be None."))

B
barrierye 已提交
355 356 357 358 359 360 361 362 363 364
        # In output_buf, different Ops (according to op_name) have different
        # cursors. In addition, there is a base_cursor. Their difference is
        # the data_idx to be taken by the corresponding Op at the current
        # time:    data_idx = consumer_cursor - base_cursor
        # 
        #            base_cursor    consumer_B_cursor (data_idx: 3)
        #                 |                       |
        # output_buf: | data0 | data1 | data2 | data3 |
        #                 |
        #   consumer_A_cursor (data_idx: 0)
365
        with self._cv:
B
barrierye 已提交
366 367 368 369
            # When the data required by the current Op is not in output_buf,
            # it is necessary to obtain a data from queue and add it to output_buf.
            while self._stop is False and self._consumer_cursors[
                    op_name] - self._base_cursor.value >= len(self._output_buf):
B
barrierye 已提交
370
                _LOGGER.debug(
371
                    self._log(
B
barrierye 已提交
372 373 374
                        "({}) B self._consumer_cursors: {}, self._base_cursor: {}, len(self._output_buf): {}".
                        format(op_name, self._consumer_cursors,
                               self._base_cursor.value, len(self._output_buf))))
375
                try:
B
barrierye 已提交
376
                    _LOGGER.debug(
377
                        self._log("{} try to get(with channel size: {})".format(
B
barrierye 已提交
378 379
                            op_name, self._que.qsize())))
                    channeldata = self._que.get(timeout=1e-3)
B
barrierye 已提交
380
                    self._output_buf.append(channeldata)
381 382
                    break
                except Queue.Empty:
B
barrierye 已提交
383
                    _LOGGER.debug(
384 385
                        self._log(
                            "{} wait for empty queue(with channel size: {})".
B
barrierye 已提交
386
                            format(op_name, self._que.qsize())))
387 388
                    self._cv.wait()

B
barrierye 已提交
389 390 391 392
            consumer_cursor = self._consumer_cursors[op_name]
            base_cursor = self._base_cursor.value
            data_idx = consumer_cursor - base_cursor
            resp = self._output_buf[data_idx]
B
barrierye 已提交
393
            _LOGGER.debug(self._log("{} get data: {}".format(op_name, resp)))
394

B
barrierye 已提交
395 396 397 398 399 400 401 402
            self._cursor_count[consumer_cursor] -= 1
            if consumer_cursor == base_cursor and self._cursor_count[
                    consumer_cursor] == 0:
                # When all the different Ops get the data that data_idx points
                # to, pop the data from output_buf.
                self._cursor_count.pop(consumer_cursor)
                self._output_buf.pop(0)
                self._base_cursor.value += 1
403 404 405 406 407 408 409 410 411 412 413 414
                # to avoid cursor overflow
                if self._base_cursor.value >= self._reset_max_cursor:
                    self._base_cursor.value -= self._reset_max_cursor
                    for name in self._consumer_cursors.keys():
                        self._consumer_cursors[name] -= self._reset_max_cursor
                    cursor_count_tmp = {
                        cursor - self._reset_max_cursor: count
                        for cursor, count in self._cursor_count.copy().items()
                    }
                    self._cursor_count.clear()
                    for cursor, count in cursor_count_tmp.items():
                        self._cursor_count[cursor] = count
B
barrierye 已提交
415 416 417 418 419 420

            self._consumer_cursors[op_name] += 1
            new_consumer_cursor = self._consumer_cursors[op_name]
            if self._cursor_count.get(new_consumer_cursor) is None:
                self._cursor_count[new_consumer_cursor] = 0
            self._cursor_count[new_consumer_cursor] += 1
421

B
barrierye 已提交
422
            _LOGGER.debug(
423
                self._log(
B
barrierye 已提交
424 425 426
                    "({}) A self._consumer_cursors: {}, self._base_cursor: {}, len(self._output_buf): {}".
                    format(op_name, self._consumer_cursors,
                           self._base_cursor.value, len(self._output_buf))))
B
barrierye 已提交
427
            _LOGGER.debug(self._log("{} notify all".format(op_name)))
428 429
            self._cv.notify_all()

B
barrierye 已提交
430
        _LOGGER.debug(self._log("multi | {} get data succ!".format(op_name)))
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        return resp  # reference, read only

    def stop(self):
        #TODO
        self.close()
        self._stop = True
        self._cv.notify_all()


class ThreadChannel(Queue.Queue):
    """ 
    (Thread version)The channel used for communication between Ops.

    1. Support multiple different Op feed data (multiple producer)
        Different types of data will be packaged through the data ID
    2. Support multiple different Op fetch data (multiple consumer)
        Only when all types of Ops get the data of the same ID,
        the data will be poped; The Op of the same type will not
        get the data of the same ID.
    3. (TODO) Timeout and BatchSize are not fully supported.

    Note:
    1. The ID of the data in the channel must be different.
    2. The function add_producer() and add_consumer() are not thread safe,
       and can only be called during initialization.
B
barrierye 已提交
456 457 458 459 460 461 462 463 464 465 466

    There are two buffers and one queue in Channel:

        op_A \                                           / op_D
        op_B - a. input_buf -> b. queue -> c. output_buf - op_E
        op_C /                                           \ op_F
    
    a. In input_buf, the input of multiple predecessor Ops is packed by data ID.
    b. The packed data will be stored in queue.
    c. In order to support multiple successor Ops to retrieve data, output_buf
        maintains the data obtained from queue.
467 468 469 470 471 472 473 474 475 476 477 478
    """

    def __init__(self, name=None, maxsize=-1, timeout=None):
        Queue.Queue.__init__(self, maxsize=maxsize)
        self._maxsize = maxsize
        self._timeout = timeout
        self.name = name
        self._stop = False

        self._cv = threading.Condition()

        self._producers = []
B
barrierye 已提交
479
        self._pushed_producer_count = {}  # {data_id: count}
B
barrierye 已提交
480
        self._input_buf = {}  # {data_id: {op_name: data}}
481

482
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
483 484 485 486
        self._consumer_cursors = {}  # {op_name: idx}
        self._cursor_count = {}  # {cursor: count}
        self._base_cursor = 0
        self._output_buf = []
487 488 489 490 491

    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
492
        return self._consumer_cursors.keys()
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

    def _log(self, info_str):
        return "[{}] {}".format(self.name, info_str)

    def debug(self):
        return self._log("p: {}, c: {}".format(self.get_producers(),
                                               self.get_consumers()))

    def add_producer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
        if op_name in self._producers:
            raise ValueError(
                self._log("producer({}) is already in channel".format(op_name)))
        self._producers.append(op_name)

    def add_consumer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
B
barrierye 已提交
510
        if op_name in self._consumer_cursors:
511 512
            raise ValueError(
                self._log("consumer({}) is already in channel".format(op_name)))
B
barrierye 已提交
513
        self._consumer_cursors[op_name] = 0
514

B
barrierye 已提交
515 516 517
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
518 519

    def push(self, channeldata, op_name=None):
B
barrierye 已提交
520
        _LOGGER.debug(
521 522 523 524 525 526 527 528 529 530 531
            self._log("{} try to push data: {}".format(op_name,
                                                       channeldata.__str__())))
        if len(self._producers) == 0:
            raise Exception(
                self._log(
                    "expected number of producers to be greater than 0, but the it is 0."
                ))
        elif len(self._producers) == 1:
            with self._cv:
                while self._stop is False:
                    try:
B
barrierye 已提交
532
                        self.put({op_name: channeldata}, timeout=0)
533 534 535 536
                        break
                    except Queue.Full:
                        self._cv.wait()
                self._cv.notify_all()
B
barrierye 已提交
537
            _LOGGER.debug(self._log("{} push data succ!".format(op_name)))
538 539 540 541 542 543 544 545 546 547
            return True
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple producers, so op_name cannot be None."))

        producer_num = len(self._producers)
        data_id = channeldata.id
        put_data = None
        with self._cv:
B
barrierye 已提交
548
            _LOGGER.debug(self._log("{} get lock".format(op_name)))
B
barrierye 已提交
549 550
            if data_id not in self._input_buf:
                self._input_buf[data_id] = {
551 552 553
                    name: None
                    for name in self._producers
                }
B
barrierye 已提交
554
                self._pushed_producer_count[data_id] = 0
B
barrierye 已提交
555
            self._input_buf[data_id][op_name] = channeldata
B
barrierye 已提交
556
            if self._pushed_producer_count[data_id] + 1 == producer_num:
B
barrierye 已提交
557 558
                put_data = self._input_buf[data_id]
                self._input_buf.pop(data_id)
B
barrierye 已提交
559
                self._pushed_producer_count.pop(data_id)
560
            else:
B
barrierye 已提交
561
                self._pushed_producer_count[data_id] += 1
562 563

            if put_data is None:
B
barrierye 已提交
564
                _LOGGER.debug(
565 566 567 568 569 570 571 572 573 574
                    self._log("{} push data succ, but not push to queue.".
                              format(op_name)))
            else:
                while self._stop is False:
                    try:
                        self.put(put_data, timeout=0)
                        break
                    except Queue.Empty:
                        self._cv.wait()

B
barrierye 已提交
575
                _LOGGER.debug(
576 577 578 579 580
                    self._log("multi | {} push data succ!".format(op_name)))
            self._cv.notify_all()
        return True

    def front(self, op_name=None):
B
barrierye 已提交
581
        _LOGGER.debug(self._log("{} try to get data".format(op_name)))
B
barrierye 已提交
582
        if len(self._consumer_cursors) == 0:
583 584 585 586
            raise Exception(
                self._log(
                    "expected number of consumers to be greater than 0, but the it is 0."
                ))
B
barrierye 已提交
587
        elif len(self._consumer_cursors) == 1:
588 589 590 591 592 593 594 595
            resp = None
            with self._cv:
                while self._stop is False and resp is None:
                    try:
                        resp = self.get(timeout=0)
                        break
                    except Queue.Empty:
                        self._cv.wait()
B
barrierye 已提交
596
            _LOGGER.debug(
597 598 599 600 601 602 603 604
                self._log("{} get data succ: {}".format(op_name, resp.__str__(
                ))))
            return resp
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple consumers, so op_name cannot be None."))

B
barrierye 已提交
605 606 607 608 609 610 611 612 613 614
        # In output_buf, different Ops (according to op_name) have different
        # cursors. In addition, there is a base_cursor. Their difference is
        # the data_idx to be taken by the corresponding Op at the current
        # time:    data_idx = consumer_cursor - base_cursor
        # 
        #            base_cursor    consumer_B_cursor (data_idx: 3)
        #                 |                       |
        # output_buf: | data0 | data1 | data2 | data3 |
        #                 |
        #   consumer_A_cursor (data_idx: 0)
615
        with self._cv:
B
barrierye 已提交
616 617 618 619
            # When the data required by the current Op is not in output_buf,
            # it is necessary to obtain a data from queue and add it to output_buf.
            while self._stop is False and self._consumer_cursors[
                    op_name] - self._base_cursor >= len(self._output_buf):
620 621
                try:
                    channeldata = self.get(timeout=0)
B
barrierye 已提交
622
                    self._output_buf.append(channeldata)
623 624 625 626
                    break
                except Queue.Empty:
                    self._cv.wait()

B
barrierye 已提交
627 628 629
            consumer_cursor = self._consumer_cursors[op_name]
            base_cursor = self._base_cursor
            data_idx = consumer_cursor - base_cursor
B
barrierye 已提交
630 631

            resp = None
632

B
barrierye 已提交
633 634 635 636 637 638
            self._cursor_count[consumer_cursor] -= 1
            if consumer_cursor == base_cursor and self._cursor_count[
                    consumer_cursor] == 0:
                # When all the different Ops get the data that data_idx points
                # to, pop the data from output_buf.
                self._cursor_count.pop(consumer_cursor)
B
barrierye 已提交
639
                resp = self._output_buf.pop(0)
B
barrierye 已提交
640
                self._base_cursor += 1
641 642 643 644 645 646 647 648 649
                # to avoid cursor overflow
                if self._base_cursor >= self._reset_max_cursor:
                    self._base_cursor -= self._reset_max_cursor
                    for name in self._consumer_cursors:
                        self._consumer_cursors[name] -= self._reset_max_cursor
                    self._cursor_count = {
                        cursor - self._reset_max_cursor: count
                        for cursor, count in self._cursor_count.items()
                    }
B
barrierye 已提交
650 651 652
            else:
                resp = copy.deepcopy(self._output_buf[data_idx])
            _LOGGER.debug(self._log("{} get data: {}".format(op_name, resp)))
B
barrierye 已提交
653 654 655 656 657 658

            self._consumer_cursors[op_name] += 1
            new_consumer_cursor = self._consumer_cursors[op_name]
            if self._cursor_count.get(new_consumer_cursor) is None:
                self._cursor_count[new_consumer_cursor] = 0
            self._cursor_count[new_consumer_cursor] += 1
659 660 661

            self._cv.notify_all()

B
barrierye 已提交
662
        _LOGGER.debug(self._log("multi | {} get data succ!".format(op_name)))
B
barrierye 已提交
663
        return resp
664 665 666 667 668 669

    def stop(self):
        #TODO
        self.close()
        self._stop = True
        self._cv.notify_all()