You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.8 KiB
55 lines
1.8 KiB
#!/usr/bin/env python3 |
|
# -*- coding: utf-8 -*- |
|
# |
|
# Copyright 2016-2099 Ailemon.net |
|
# |
|
# This file is part of ASRT Speech Recognition Tool. |
|
# |
|
# ASRT is free software: you can redistribute it and/or modify |
|
# it under the terms of the GNU General Public License as published by |
|
# the Free Software Foundation, either version 3 of the License, or |
|
# (at your option) any later version. |
|
# ASRT is distributed in the hope that it will be useful, |
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
# GNU General Public License for more details. |
|
# |
|
# You should have received a copy of the GNU General Public License |
|
# along with ASRT. If not, see <https://www.gnu.org/licenses/>. |
|
# ============================================================================ |
|
|
|
""" |
|
@author: nl8590687 |
|
解决python生成器多线程的线程安全问题 |
|
""" |
|
|
|
import threading |
|
''' |
|
A generic iterator and generator that takes any iterator and wrap it to make it thread safe. |
|
This method was introducted by Anand Chitipothu in http://anandology.com/blog/using-iterators-and-generators/ |
|
but was not compatible with python 3. This modified version is now compatible and works both in python 2.8 and 3.0 |
|
''' |
|
|
|
|
|
class threadsafe_iter: |
|
"""Takes an iterator/generator and makes it thread-safe by |
|
serializing call to the `next` method of given iterator/generator. |
|
""" |
|
def __init__(self, it): |
|
self.it = it |
|
self.lock = threading.Lock() |
|
|
|
def __iter__(self): |
|
return self |
|
|
|
def __next__(self): |
|
with self.lock: |
|
return self.it.__next__() |
|
|
|
|
|
def threadsafe_generator(f): |
|
"""A decorator that takes a generator function and makes it thread-safe. |
|
""" |
|
def g(*a, **kw): |
|
return threadsafe_iter(f(*a, **kw)) |
|
return g
|
|
|