當前位置: 首頁>>代碼示例>>Python>>正文


Python Condition.wait方法代碼示例

本文整理匯總了Python中multiprocessing.Condition.wait方法的典型用法代碼示例。如果您正苦於以下問題:Python Condition.wait方法的具體用法?Python Condition.wait怎麽用?Python Condition.wait使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在multiprocessing.Condition的用法示例。


在下文中一共展示了Condition.wait方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __call__

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
    def __call__(self, cv_iterator, evaluator, fold_callback=None,
                 n_jobs=None):
        """
        """
        condvar = Condition()
        results = []

        def _signal_cb(result):
            condvar.acquire()
            results.append(result)
            condvar.notify()
            condvar.release()
        folds = list(cv_iterator)

        pool, deferreds = self.async(folds, evaluator,
                                     fold_callback=_signal_cb, n_jobs=n_jobs)
        pool.close()
        while len(results) < len(folds):
            condvar.acquire()
            condvar.wait()
            fold_estimator, result = results[-1]
            fold_callback(fold_estimator, result)
            condvar.release()
        pool.join()
        return results
開發者ID:ihaque,項目名稱:grizzly,代碼行數:27,代碼來源:multiprocess.py

示例2: test_watch_directory

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
def test_watch_directory():

    def _cleanup(path):
        for f in listdir(path):
            p = join(path, f)
            if isdir(p):
                rmtree(p)
            elif f != '.nothing':
                unlink(p)

    sample_template = ''
    sample_directory = dirname(realpath(__file__)) + '/sample/'
    watch_directory = sample_directory + 'watch/'
    render_directory = sample_directory + 'render/'
    template_directory = sample_directory + 'templates/'
    with open(template_directory + 'haml.tmpl', 'r') as f:
        sample_template = f.read()

    condition = Condition()
    p = Process(target=reloader.watch_directory,
                args=(watch_directory, render_directory, condition))
    condition.acquire()
    p.start()
    condition.wait()

    try:
        with open(watch_directory + 'test.haml', 'w') as f:
            f.write(sample_template)

        subdir = watch_directory + 'test_subdir/'
        try:
            mkdir(subdir)
        except OSError:
            if not isdir(subdir):
                raise
        with open(subdir + 'test_two.haml', 'w') as f:
            f.write(sample_template)

        sleep(1)

        assert_true(exists(render_directory + 'test.html'))
        assert_true(exists(render_directory + 'test_subdir/test_two.html'))
    except:
        raise
    finally:
        condition.release()
        p.terminate()
        p.join()

        sleep(1)

        _cleanup(watch_directory)
        _cleanup(render_directory)
開發者ID:petermelias,項目名稱:hamlreloader,代碼行數:55,代碼來源:test_reloader.py

示例3: Barrier

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class Barrier(object):
    def __init__(self, num_threads):
        self.num_threads = num_threads
        self.threads_left = Value('i', num_threads, lock=True)
        self.mutex = Lock()
        self.waitcond = Condition(self.mutex)

    def wait(self):
        self.mutex.acquire()
        self.threads_left.value -= 1
        if self.threads_left.value == 0:
            self.threads_left.value = self.num_threads
            self.waitcond.notify_all()
            self.mutex.release()
        else:
            self.waitcond.wait()
            self.mutex.release()
開發者ID:Jailander,項目名稱:mongodb_store,代碼行數:19,代碼來源:mongodb_log.py

示例4: OrderedQueue

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class OrderedQueue(object):
    def __init__(self, maxsize):
        self.queue = Queue(maxsize=maxsize)
        self.lock = Lock()
        self.getlock = Lock()
        self.putcounter = Value('i', -1)
        self.getcounter = Value('i', 0)
        self.cond = Condition(self.lock)
        self.manager = Manager()
        self.getlist = self.manager.list()

    def put(self, index, elem):
        with self.lock:
            while index != self.putcounter.value + 1:
                self.cond.wait()
            self.queue.put((index, elem))
            #sys.stderr.write("right after adding data with SEED %i. Queue size is now %i\n" %(index, self.queue.qsize()))
            self.putcounter.value += 1
            self.cond.notify_all()
        
    def get(self):
        with self.getlock:
            for i, element in enumerate(self.getlist):
                index, elem = element 
                if index == self.getcounter.value:
                    self.getcounter.value += 1
                    del self.getlist[i]
                    return (index, elem)
            while True:
                index, elem = self.queue.get()
                if index == self.getcounter.value:
                    self.getcounter.value += 1
                    return (index, elem)
                else:
                    self.getlist.append((index, elem))

    def close(self):
        return self.queue.close()

    def qsize(self):
        return self.queue.qsize()
開發者ID:SinaHonari,項目名稱:RCN,代碼行數:43,代碼來源:queue.py

示例5: CountBucket

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class CountBucket(Query):
    """
    Class for registering callbacks on counts of packets sent to
    the controller.
    """
    def __init__(self):
        super(CountBucket, self).__init__()
        self.matches = set([])
        self.runtime_stats_query_fun = None
        self.outstanding_switches = []
        self.packet_count = 0
        self.byte_count = 0
        self.packet_count_persistent = 0
        self.byte_count_persistent = 0
        self.in_update_cv = Condition()
        self.in_update = False
        self._classifier = self.generate_classifier()
        
    def __repr__(self):
        return "CountBucket"

    def eval(self, pkt):
        """
        evaluate this policy on a single packet

        :param pkt: the packet on which to be evaluated
        :type pkt: Packet
        :rtype: set Packet
        """
        return set()

    def generate_classifier(self):
        return Classifier([Rule(identity,{self})])

    def apply(self):
        with self.bucket_lock:
            for pkt in self.bucket:
                self.packet_count_persistent += 1
                self.byte_count_persistent += pkt['header_len'] + pkt['payload_len']
            self.bucket.clear()

    def start_update(self):
        """
        Use a condition variable to mediate access to bucket state as it is
        being updated.

        Why condition variables and not locks? The main reason is that the state
        update doesn't happen in just a single function call here, since the
        runtime processes the classifier rule by rule and buckets may be touched
        in arbitrary order depending on the policy. They're not all updated in a
        single function call. In that case,

        (1) Holding locks *across* function calls seems dangerous and
        non-modular (in my opinion), since we need to be aware of this across a
        large function, and acquiring locks in different orders at different
        points in the code can result in tricky deadlocks (there is another lock
        involved in protecting bucket updates in runtime).

        (2) The "with" semantics in python is clean, and splitting that into
        lock.acquire() and lock.release() calls results in possibly replicated
        failure handling code that is boilerplate.

        """
        with self.in_update_cv:
            self.in_update = True
            self.matches = set([])
            self.runtime_stats_query_fun = None
            self.outstanding_switches = []

    def finish_update(self):
        with self.in_update_cv:
            self.in_update = False
            self.in_update_cv.notify_all()
        
    def add_match(self, m):
        """
        Add a match m to list of classifier rules to be queried for
        counts.
        """
        if not m in self.matches:
            self.matches.add(m)

    def add_pull_stats(self, fun):
        """
        Point to function that issues stats queries in the
        runtime.
        """
        if not self.runtime_stats_query_fun:
            self.runtime_stats_query_fun = fun

    def pull_stats(self):
        """Issue stats queries from the runtime"""
        queries_issued = False
        with self.in_update_cv:
            while self.in_update: # ensure buckets not updated concurrently
                self.in_update_cv.wait()
            if not self.runtime_stats_query_fun is None:
                self.outstanding_switches = []
                queries_issued = True
                self.runtime_stats_query_fun()
#.........這裏部分代碼省略.........
開發者ID:09beeihaq,項目名稱:Coursera-SDN-Assignments,代碼行數:103,代碼來源:language.py

示例6: TProcessPoolServer

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class TProcessPoolServer(TServer):

    """
    Server with a fixed size pool of worker subprocesses which service requests.
    Note that if you need shared state between the handlers - it's up to you!
    Written by Dvir Volk, doat.com
    """

    def __init__(self, * args):
        TServer.__init__(self, *args)
        self.numWorkers = 10
        self.workers = []
        self.isRunning = Value('b', False)
        self.stopCondition = Condition()
        self.postForkCallback = None

    def setPostForkCallback(self, callback):
        if not callable(callback):
            raise TypeError("This is not a callback!")
        self.postForkCallback = callback

    def setNumWorkers(self, num):
        """Set the number of worker threads that should be created"""
        self.numWorkers = num

    def workerProcess(self):
        """Loop around getting clients from the shared queue and process them."""

        if self.postForkCallback:
            self.postForkCallback()

        while self.isRunning.value == True:
            try:
                client = self.serverTransport.accept()
                self.serveClient(client)
            except (KeyboardInterrupt, SystemExit):
                return 0
            except (Exception) as x:
                logging.exception(x)

    def serveClient(self, client):
        """Process input/output from a client for as long as possible"""
        itrans = self.inputTransportFactory.getTransport(client)
        otrans = self.outputTransportFactory.getTransport(client)
        iprot = self.inputProtocolFactory.getProtocol(itrans)
        oprot = self.outputProtocolFactory.getProtocol(otrans)

        try:
            while True:
                self.processor.process(iprot, oprot)
        except (TTransportException) as tx:
            pass
        except (Exception) as x:
            logging.exception(x)

        itrans.close()
        otrans.close()


    def serve(self):
        """Start a fixed number of worker threads and put client into a queue"""

        #this is a shared state that can tell the workers to exit when set as false
        self.isRunning.value = True

        #first bind and listen to the port
        self.serverTransport.listen()

        #fork the children
        for i in range(self.numWorkers):
            try:
                w = Process(target=self.workerProcess)
                w.daemon = True
                w.start()
                self.workers.append(w)
            except (Exception) as x:
                logging.exception(x)

        #wait until the condition is set by stop()

        while True:

            self.stopCondition.acquire()
            try:
                self.stopCondition.wait()
                break
            except (SystemExit, KeyboardInterrupt):
		break
            except (Exception) as x:
                logging.exception(x)

        self.isRunning.value = False

    def stop(self):
        self.isRunning.value = False
        self.stopCondition.acquire()
        self.stopCondition.notify()
        self.stopCondition.release()
開發者ID:csabahruska,項目名稱:lambdacube.addon,代碼行數:100,代碼來源:TProcessPoolServer.py

示例7: IODeviceManager

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class IODeviceManager(Thread):

    def __init__(self, a_device, a_kernel, std_in=StandardInput(), std_out=StandardOutput()):
        Thread.__init__(self)
        self.set_device(a_device)
        self.set_kernel(a_kernel)
        self.set_input(std_in)
        self.set_output(std_out)
        self.set_mutex(RLock())
        self.set_queue(SoQueue())
        self.device_is_in_use = Condition(self.get_mutex())
        self.the_queue_is_empty = Condition(self.get_mutex())

    def get_kernel(self):
        return self.kernel

    def set_kernel(self, a_kernel):
        self.kernel = a_kernel

    def set_input(self, a_input):
        self.std_in = a_input

    def get_input(self):
        return self.std_in

    def set_output(self, a_output):
        self.std_out = a_output

    def get_output(self):
        return self.std_out

    def get_mutex(self):
        return self.mutex
        
    def set_mutex(self, a_mutex):   
        self.mutex = a_mutex
        
    def get_queue(self):
        return self.queue
        
    def set_queue(self, a_queue):
        self.queue = a_queue
    
    def set_device(self, a_device):
        self.device = a_device
        self.get_device().set_device_manager(self)

    def get_device(self):
        return self.device
        
    def the_device_is_busy(self):
        with self.get_mutex():
            return not self.get_device().is_not_busy()
    
    def send_to_device(self):
        with self.device_is_in_use:
            while self.the_device_is_busy():
                self.device_is_in_use.wait()
            with self.get_mutex():
                self.get_device().set_pcb(self.get())
                self.get_device().process_pcb()

    def notify_that_the_device_is_not_in_use(self):
        with self.device_is_in_use:
            self.device_is_in_use.notify()
    
    def put(self, a_pcb):
        with self.the_queue_is_empty:
            with self.get_mutex():
                self.get_queue().add_pcb(a_pcb)
                self.the_queue_is_empty.notify()
        
    def get(self):
        with self.get_mutex():
            return self.get_queue().get_first()

    def queue_is_empty(self):
        return self.get_queue().is_empty()

    def send_io_end_interruption(self, a_pcb):
        self.get_kernel().get_irq_manager().handle(Irq(IO_END_INTERRUPT,  a_pcb))
            
    def run(self):
        while True:
            with self.the_queue_is_empty:
                while self.queue_is_empty():
                    self.the_queue_is_empty.wait()
                self.send_to_device()
開發者ID:danwyryunq,項目名稱:TPSOUNQ,代碼行數:90,代碼來源:IODeviceManager.py

示例8: int

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
                    if line == '':
                        continue
                    idx = int(line[:line.find(' ')])
                    line = line[line.find(' ') + 1:]
                    if idx != 1 or full_ex == '':
                        full_ex = full_ex + line + '\n'
                        continue  # next line
                    else:
                        cnt_exs += 1
                        load(full_ex.strip())
                        if args['n'] is not None and cnt_exs >= args['n']:
                            full_ex = ''
                            break
                        full_ex = line + '\n'
                # process last full_ex if out of new lines
                if full_ex != '':
                    load(full_ex.strip())

    while queued_exs.value - proced_exs.value > 0:
        with finished:
            finished.wait()

for t in threads:
    t.terminate()

fin = time.time()

print('Time processing entities: {} s'.format(round(mid - beg)))
print('Time processing examples: {} s'.format(round(fin - mid)))
print('Total time: {} s'.format(round(fin - beg)))
開發者ID:cdj0311,項目名稱:nlp-architect,代碼行數:32,代碼來源:wikiwindows.py

示例9: DBPipeline

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]

#.........這裏部分代碼省略.........

    def stop(self):
        """
        Force the next() method to return while in another thread.
        The return value of next() will be None.
        """
        with self.condition:
            self.running = False
            self.condition.notify_all()

    def pause(self):
        with self.condition:
            self.paused = True
            self.condition.notify_all()

    def unpause(self):
        with self.condition:
            self.paused = False
            self.condition.notify_all()

    def sleep(self, item):
        assert id(item) in self.all
        with self.condition:
            self.sleeping.add(item)
            self.condition.notify_all()

    def wake(self, item):
        assert id(item) in self.all
        assert item in self.sleeping
        with self.condition:
            self.sleeping.remove(item)
            self.condition.notify_all()

    def wait_for_id(self, item_id):
        with self.condition:
            while self.has_id(item_id):
                self.condition.wait()

    def wait(self):
        """
        Waits for all currently running tasks to complete.
        """
        with self.condition:
            while self.working:
                self.condition.wait()

    def wait_all(self):
        """
        Waits for all queued and running tasks to complete.
        """
        with self.condition:
            while len(self) > 0:
                self.condition.wait()

    def with_lock(self, function, *args, **kwargs):
        with self.condition:
            return function(self, *args, **kwargs)

    def set_max_working(self, max_working):
        with self.condition:
            self.max_working = int(max_working)
            self.condition.notify_all()

    def get_max_working(self):
        return self.max_working
開發者ID:0x24bin,項目名稱:exscript,代碼行數:69,代碼來源:DBPipeline.py

示例10: IOManager

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class IOManager(object):
    def __init__(self):
        self.capture_mode = False
        self.child_mode = False
        self.parent_mode = False

    def activate_as_child(self, output_lock, output_queue, status_line_cleared):
        self.parent_mode = False
        self.child_mode = True
        self.status_line_cleared = status_line_cleared
        self.output_lock = output_lock
        self.output_queue = output_queue

    def activate_as_parent(self, debug=False):
        assert not self.child_mode
        self.debug_mode = debug
        self.jobs = []
        self.output_lock = Lock()
        self.parent_mode = True
        self.output_queue = Queue()
        self.status_line_cleared = Condition()
        self.thread = Thread(target=self._print_thread)
        self.thread.daemon = True
        self.thread.start()

    def ask(self, question, default, get_input=input_function):
        answers = _("[Y/n]") if default else _("[y/N]")
        question = question + " " + answers + " "
        with self.lock:
            while True:
                STDOUT_WRITER.write("\a")
                STDOUT_WRITER.write(question)
                STDOUT_WRITER.flush()

                answer = get_input()
                if answer.lower() in (_("y"), _("yes")) or (
                    not answer and default
                ):
                    return True
                elif answer.lower() in (_("n"), _("no")) or (
                    not answer and not default
                ):
                    return False
                STDOUT_WRITER.write(_("Please answer with 'y(es)' or 'n(o)'.\n"))

    @contextmanager
    def capture(self):
        self.capture_mode = True
        self.captured_io = {
            'stderr': "",
            'stdout': "",
        }
        yield self.captured_io
        self.capture_mode = False

    @property
    def child_parameters(self):
        return (self.output_lock, self.output_queue, self.status_line_cleared)

    def debug(self, msg):
        self.output_queue.put({'msg': 'LOG', 'log_type': 'DBG', 'text': msg})

    def job_add(self, msg):
        self.output_queue.put({'msg': 'LOG', 'log_type': 'JOB_ADD', 'text': msg})

    def job_del(self, msg):
        self.output_queue.put({'msg': 'LOG', 'log_type': 'JOB_DEL', 'text': msg})

    def stderr(self, msg):
        self.output_queue.put({'msg': 'LOG', 'log_type': 'ERR', 'text': msg})

    def stdout(self, msg):
        self.output_queue.put({'msg': 'LOG', 'log_type': 'OUT', 'text': msg})

    @contextmanager
    def job(self, job_text):
        self.job_add(job_text)
        yield
        self.job_del(job_text)

    @property
    @contextmanager
    def lock(self):
        with self.output_lock:
            self.status_line_cleared.wait()
            yield

    def _print_thread(self):
        assert self.parent_mode
        while True:
            if self.output_lock.acquire(False):
                msg = self.output_queue.get()
                if msg['log_type'] == 'QUIT':
                    break
                if self.debug_mode and msg['log_type'] in ('OUT', 'DBG', 'ERR'):
                    msg['text'] = datetime.now().strftime("[%Y-%m-%d %H:%M:%S.%f] ") + msg['text']
                if self.jobs and TTY:
                    self._write("\r\033[K")
                if msg['log_type'] == 'OUT':
                    self._write(msg['text'] + "\n")
#.........這裏部分代碼省略.........
開發者ID:sq3,項目名稱:bundlewrap,代碼行數:103,代碼來源:ui.py

示例11: Pipeline

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]

#.........這裏部分代碼省略.........
        Force the next() method to return while in another thread.
        The return value of next() will be None.
        """
        with self.condition:
            self.running = False
            self.condition.notify_all()

    def start(self):
        with self.condition:
            self.running = True
            self.condition.notify_all()

    def pause(self):
        with self.condition:
            self.paused = True
            self.condition.notify_all()

    def unpause(self):
        with self.condition:
            self.paused = False
            self.condition.notify_all()

    def sleep(self, item):
        with self.condition:
            self.sleeping.add(item)
            self.condition.notify_all()

    def wake(self, item):
        assert item in self.sleeping
        with self.condition:
            self.sleeping.remove(item)
            self.condition.notify_all()

    def wait_for_id(self, item_id):
        with self.condition:
            while self.has_id(item_id):
                self.condition.wait()

    def wait(self):
        """
        Waits for all currently running tasks to complete.
        """
        with self.condition:
            while self.working:
                self.condition.wait()

    def wait_all(self):
        """
        Waits for all queued and running tasks to complete.
        """
        with self.condition:
            while len(self) > 0:
                self.condition.wait()

    def with_lock(self, function, *args, **kwargs):
        with self.condition:
            return function(self, *args, **kwargs)

    def set_max_working(self, max_working):
        with self.condition:
            self.max_working = int(max_working)
            self.condition.notify_all()

    def get_max_working(self):
        return self.max_working
開發者ID:0x24bin,項目名稱:exscript,代碼行數:69,代碼來源:Pipeline.py

示例12: WaitableQueue

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class WaitableQueue(Queue):
    """Queue that uses a semaphore to reliably count items in it"""
    class Vacuum(ThreadLoop):
        def __init__(self, q, l):
            def callback():
                q.wait_notempty(0.1)

                while True:
                    try:
                        val = q.get(False)
                        l.append(val)

                    except Empty:
                        break

            ThreadLoop.__init__(self, callback)

    def __init__(self, maxsize=0):
        self.cond_empty = Condition()
        self.cond_notempty = Condition()
        self._put_counter = Value('i', 0)

        Queue.__init__(self, maxsize)

    def put(self, obj, block=True, timeout=None):
        Queue.put(self, obj, block, timeout)
        self._put_counter.value += 1

        if self.qsize() != 0:
            self.cond_notempty.acquire()
            try:
                self.cond_notempty.notify_all()
            finally:
                self.cond_notempty.release()

    @property
    def put_counter(self):
        return self._put_counter.value

    def get(self, block=True, timeout=None):
        ret = Queue.get(self, block, timeout)
        if self.qsize() == 0:
            self.cond_empty.acquire()
            try:
                self.cond_empty.notify_all()
            finally:
                self.cond_empty.release()

        return ret

    def wait_empty(self, timeout=None):
        """Wait for all items to be got"""
        self.cond_empty.acquire()
        try:
            if self.qsize():
                self.cond_empty.wait(timeout)
        finally:
            self.cond_empty.release()

    def wait_notempty(self, timeout=None):
        """Wait for all items to be got"""
        self.cond_notempty.acquire()
        try:
            if self.qsize() == 0:
                self.cond_notempty.wait(timeout)
        finally:
            self.cond_notempty.release()
開發者ID:OnGle,項目名稱:turnkey-pylib,代碼行數:69,代碼來源:multiprocessing_utils.py

示例13: range

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
    if args.train:
        if sizes:
            problems_to_solve = itertools.islice(itertools.imap(api.train, itertools.cycle(sizes)), args.train_amount)
        else:
            problems_to_solve = (api.train(6) for i in range(args.train_amount))
    else:
        if sizes:
            problems_to_solve = filter(lambda p: p['size'] in sizes, original_problems)
        else:
            problems_to_solve = original_problems

    cond = Condition()

    for problem in problems_to_solve:
        slave = Process(target=submitter.submit_in_sandbox, args=(problem, True, cond))
        cond.acquire()
        slave.start()

        print "MASTER: waiting for process to exhaust its variants."
        cond.wait(300)
        cond.release()

        if slave.is_alive():
            print "MASTER: worker tried hard but no success so far. Letting him stay for a while."

    while active_children():
        children = active_children()
        print "PROCESSES LEFT:", children
        for c in children:
            c.join(timeout=60)
開發者ID:vbo,項目名稱:icfp2013,代碼行數:32,代碼來源:submitter_manager.py

示例14: RWLock

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class RWLock():
    """A Readers-Writer lock.
    
    Allows for multiple readers or one writer. Writers will not starve.

    Attributes:
        for_reading (RWLock.ReadLock): A lock-like object with appropriate
            `acquire`, `release`, `__enter__` and `__exit__` methods pointed
            to the *read methods of the RWLock. Chiefly for use with the 
            `with` statement.
        for_writing (RWLock.WriteLock): A lock-like object with appropriate
            `acquire`, `release`, `__enter__` and `__exit__` methods pointed
            to the *write methods of the RWLock. Chiefly for use with the 
            `with` statement.

    """
    class ReadLock():
        def __init__(self, rw):
            self._rw = rw
            self.acquire = rw.acquire_read
            self.release = rw.release_read
        def __enter__(self):
            self.acquire()
        def __exit__(self, exception_type, exception_value, traceback):
            self.release()

    class WriteLock():
        def __init__(self, rw):
            self._rw = rw
            self.acquire = rw.acquire_write
            self.release = rw.release_write
        def __enter__(self):
            self.acquire()
        def __exit__(self, exception_type, exception_value, traceback):
            self.release()

    def __init__(self):
        """Initialises the RWLock."""
        self._condition = Condition()
        self._readers = Value(c_uint64, 0, lock=False)
        self._writers_waiting = Value(c_uint64, 0, lock=False)

        self.for_reading = self.ReadLock(self)
        self.for_writing = self.WriteLock(self)

    def acquire_read(self):
        """Acquire a read lock. 
        
        Blocks if a thread has acquired the write lock or is waiting to
        acquire the write lock.
        
        """
        with self._condition:
            while self._writers_waiting.value:
                self._condition.wait()
            self._readers.value += 1

    def release_read(self):
        """Release a read lock."""
        with self._condition:
            self._readers.value -= 1
            if not self._readers.value:
                self._condition.notify_all()

    def acquire_write(self):
        """Acquire a write lock.
        
        Blocks until there are no acquired read or write locks.
        
        """
        self._condition.acquire()
        self._writers_waiting.value += 1
        while self._readers.value:
            self._condition.wait()
        self._writers_waiting.value -= 1

    def release_write(self):
        """Release a write lock."""
        self._condition.release()
開發者ID:PaperclipBadger,項目名稱:hadamardequivalence,代碼行數:81,代碼來源:concurrencyutils.py

示例15: Cpu

# 需要導入模塊: from multiprocessing import Condition [as 別名]
# 或者: from multiprocessing.Condition import wait [as 別名]
class Cpu(object):

    def __init__(self):

        self.pcb = None

        self.__mutex = RLock()
        self.__pcb_not_set = Condition(self.__mutex)
        self.__mem_not_allocated = Condition(self.__mutex)
        self.__round_robin_policy_on = False


    def enable_round_robin(self, round_robin_quantum):
        self.__round_robin_policy_on = True
        self.__round_robin = RoundRobin(round_robin_quantum)

    def pcb_not_set(self):
        return self.__pcb_not_set


    def set_kernel(self, kernel):
        self.__kernel = kernel

    def is_pcb_set(self):
        return self.pcb != None

    def set_current_pcb(self, pcb):
        with self.__pcb_not_set:
            self.pcb = pcb
            self.__pcb_not_set.notify()

    def reset_pcb(self):
        self.pcb = None

    def get_current_pcb(self):
        return self.pcb

    def __get_mem_manager(self):
        return self.__kernel.get_mem_manager()

    def __get_irq_manager(self):
        return self.__kernel.get_irq_manager()

    def fetch_decode_and_execute(self):
        with self.__pcb_not_set:
            while(not self.is_pcb_set()):
                self.__pcb_not_set.wait()

            with self.__mutex:
                self.__fetch()
                self.__decode()
                self.__execute()

    def __fetch(self):
        pcb = self.get_current_pcb()
        address = self.__get_mem_manager().current_instruction_address(pcb)
        with self.__mem_not_allocated:
            while self.__get_mem_manager().get(pcb,address) == None:
                self.__mem_not_allocated.wait()
            self.__current_instruction = self.__get_mem_manager().get(pcb, address )

    def __decode(self):
        self.__send_interruption_if_is_io()
        self.__send_interruption_if_is_kill()

    def __send_interruption_if_is_kill(self):
        if(self.__current_instruction.is_kill_instruction()):
            self.send_end()

    def __send_interruption_if_is_io(self):
        if(self.__current_instruction.is_io_instruction()):
            self.send_io()

    def __execute(self):
        self.__execute_if_is_cpu_instruction()

    def __execute_if_is_cpu_instruction(self):
        if (self.__current_instruction.is_cpu_instruction()):
            self.__current_instruction.run()
            self.get_current_pcb().increment_pc()

    def send_interruption(self, a_interruption):
        self.__get_irq_manager().handle(Irq(a_interruption, self.get_current_pcb()))

    def send_timeout(self):
        self.send_interruption(TIMEOUT_INTERRUPT)

    def send_end(self):
        self.send_interruption(KILL_INTERRUPT)

    def send_io(self):
        self.send_interruption(IO_INTERRUPT)

    def on_signal(self):
        if self.__round_robin_policy_on:
            self.__round_robin.handle_action(self)
        else:
            self.fetch_decode_and_execute()
開發者ID:danwyryunq,項目名稱:TPSOUNQ,代碼行數:100,代碼來源:Cpu.py


注:本文中的multiprocessing.Condition.wait方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。