当前位置: 首页>>代码示例>>Python>>正文


Python Semaphore.release方法代码示例

本文整理汇总了Python中threading.Semaphore.release方法的典型用法代码示例。如果您正苦于以下问题:Python Semaphore.release方法的具体用法?Python Semaphore.release怎么用?Python Semaphore.release使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在threading.Semaphore的用法示例。


在下文中一共展示了Semaphore.release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PromptService

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class PromptService(object):
    def __init__(self):
        self.semaphore = Semaphore(0)
        self.commandWindow = None
        self.response = None

    def setCommandWindow(self, window):
        self.commandWindow = window

    def requestInput(self, prompt):
        if self.commandWindow is None:
            raise RuntimeError("Command window hasn't registered itself")
        if prompt is None:
            prompt = ''

        self.commandWindow.prompt(prompt, 'standard-output', self.respond, 'standard-input')
        self.semaphore.acquire()

        if self.response is None:
            raise KeyboardInterrupt
        else:
            res = self.response
            self.response = None
            return str(res)

    def respond(self, value):
        self.response = value
        self.semaphore.release()
开发者ID:HenryStevens,项目名称:jes,代码行数:30,代码来源:prompt.py

示例2: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class Wc:
    def __init__(self):
        self.flush()

    def flush(self):
        self.sem = Semaphore(1)
        self.user = None
        self.waiting = []

    def used_by(self, who):
        self.user = who
        self.waiting.remove(who)

    def being_used_by(self, who):
        return self.user == who

    def acquire(self, a):
        return self.sem.acquire(a)

    def release(self):
        self.user = None
        self.sem.release()

    def enqueue(self, nick):
        self.waiting.append(nick)

    def is_waiting(self, nick):
        return (nick in self.waiting)
    def who(self):
        return self.user
开发者ID:RetroRodent,项目名称:my-gozerbot,代码行数:32,代码来源:wc.py

示例3: Request_deque

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class Request_deque():
    from collections import deque
    def __init__(self, value=1):
        self.sema = Semaphore(value)
        self.time_stamp_q = deque()
        self.sync_lock = Lock()
    
    def acquire(self, blocking=True):
        if self.sema.acquire(blocking):
            # released under blocked mode or happened to have spare under
            #non-blocking mode
            return True, self.time_stamp_q.popleft()
        else:                    
            # non-blocking mode with unsuccessful acquiring
            return False, None
    
    def release(self, stop=False):
        with self.sync_lock:
            # need to guarantee the order matching between request and time
            #stamp, the operation shall be atomic. This could be rare to have
            #but unaffordable if any.
            if stop:
                self.time_stamp_q.append(None)
            else:
                self.time_stamp_q.append(dt.now())
            self.sema.release()
开发者ID:chxzh,项目名称:shadyn,代码行数:28,代码来源:rendering_rf.py

示例4: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class StatisticQueue:
    def __init__(self, stats):
        self._semaphore = Semaphore()
        self.result = {}
        self.stats = stats

    def write_result(self, data):
        self._semaphore.acquire()
        self.result.update(data)
        self._semaphore.release()

    def start_parse(self):
        self.stats.connect()
        self.stats.init_message_stack()
        func_to_start = [
            self.stats.get_top3_speakers,
            self.stats.get_most_frequent_youtube_video,
            self.stats.get_time_activity,
            self.stats.get_abusive_expressions,
        ]
        threads = []
        for func in func_to_start:
            thread = Thread(target=func, args=(self, ))
            threads.append(thread)
            thread.start()
        for t in threads:
            t.join()
        return self.result
开发者ID:saucebwz,项目名称:DjangoConferenceStatistics,代码行数:30,代码来源:StatisticQueue.py

示例5: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class VDOM_mutex:
	""" This class should be used to lock objects """

	def __init__(self):
		""" Constructor """
		self.__mutex = Semaphore(1)
#	self.__mutex = RLock();
#	self.__counter = 0
#	self.__trylock = Lock();

	def lock(self):
		""" Lock object """
		self.__mutex.acquire()
#	self.__counter = self.__counter + 1
#	return self.__counter

	def unlock(self):
		""" Unlock object """
#	self.__trylock.acquire()

#	cntr = self.__counter
#	if cntr:
#	    self.__mutex.release()	
#	    self.__counter = self.__counter - 1
#	    cntr = self.__counter

		self.__mutex.release()
开发者ID:VDOMBoxGroup,项目名称:runtime2.0,代码行数:29,代码来源:mutex.py

示例6: JobManager

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class JobManager(LogMaster):
    """
    keeps a queue of jobs, and runs them in a separate thread, while keeping the number of worker thread under
    a specified treshold.
    it is not a real thread pool as new thread are fired every time
    """

    def __init__(self, maxthreads, loglevel=logging.INFO):
        self.setLogger(self.__class__.__name__, loglevel)
        self.maxthreads = maxthreads
        self.semaph = Semaphore(value=self.maxthreads)
        self.jobq = Queue()
        self.running = True
        self.dispatcher = Thread(target=self._jobdispatcher, daemon=True)
        self.dispatcher.start()

    def putjob(self, job):
        self.jobq.put(job)

    def harness(self, job):
        job.execute()
        self.semaph.release()

    def _jobdispatcher(self):
        self.logger.debug("Started job dispatcher thread")
        while self.running:
            self.semaph.acquire()
            job = self.jobq.get()
            if job is None:
                self.semaph.release()
                continue
            t = Thread(target=self.harness, args=(job,), daemon=True)
            t.start()
        self.logger.debug("Stopped job dispatcher thread")
开发者ID:agentOfChaos,项目名称:ichigo-short-cake,代码行数:36,代码来源:job_manager.py

示例7: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class ThreadMaster:
    '''
    classdocs
    '''
    
    def __init__(self, maxThreads):
        self.maxThreads = maxThreads
        self.freeThreads = Semaphore(value=self.maxThreads)

    def waitUntilAllReady(self):

        for c in range(0, self.maxThreads ):
            self.freeThreads.acquire()

        for c in range(0, self.maxThreads ):
            self.freeThreads.release()


    def startFunction(self, fun, ar ):
        newThread = Thread(target=fun, args=ar)
        self.freeThreads.acquire()
        newThread.start()

    def done(self):
        self.freeThreads.release();
开发者ID:TopiKo,项目名称:BendAndSlide,代码行数:27,代码来源:test.py

示例8: FadeInTransition

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class FadeInTransition(XiboTransition):
    "Abstract Class - Interface for Transitions"

    def run(self):
        self.lock = Semaphore()
        self.lock.acquire()

        if not self.media1 is None:
            if self.options1["transOutDuration"] > 0:
                self.outDuration = int(self.options1["transOutDuration"])
            else:
                self.outDuration = 1000

            self.p.enqueue("setOpacity", (self.media1.getName(), 0.0))
            self.p.enqueue("anim", ("fadeIn", self.media1.getName(), self.outDuration, self.next))
            self.lock.acquire()

        if not self.media2 is None:
            self.media2.start()

        if not self.media2 is None:
            if self.options2["transInDuration"] > 0:
                self.inDuration = int(self.options2["transInDuration"])
            else:
                self.inDuration = 1000

            self.p.enqueue("setOpacity", (self.media2.getName(), 0.0))
            self.p.enqueue("anim", ("fadeIn", self.media2.getName(), self.inDuration, self.next))
            self.lock.acquire()

        self.callback()

    def next(self):
        self.lock.release()
开发者ID:bertsmit,项目名称:pythonclient,代码行数:36,代码来源:FadeInTransition.py

示例9: CollapseTransition

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class CollapseTransition(XiboTransition):

    def run(self):
        self.lock = Semaphore()
        self.lock.acquire()

        # Only valid as an exit transition

        if self.media1 != None:
            if self.options1['transOutDuration'] > 0:
                self.outDuration = int(self.options1['transOutDuration'])
            else:
                self.outDuration = 1000

            self.__animate__(self.media1.getName(),self.media1.getX(), self.media1.getY(),self.media1.getWidth(),self.media1.getHeight(),self.outDuration,self.next)
            self.lock.acquire()

        self.callback()

    def next(self):
        self.lock.release()

    def __animate__(self,name,currentX,currentY,w,h,duration,callback):
        # ('ease', nodeName, animation duration, animation attribute, start position, finish position, callback on Stop, easeIn duration, easeOut duration)
        self.log.log(5,"info","CollapseTransition: Collapsing " + name + " over " + str(duration) + "ms")
        self.p.enqueue('anim',('linear',name,duration,'y',currentY,int(h/2),None))
        self.p.enqueue('anim',('linear',name,duration,'height',int(h),0,callback))
        self.p.enqueue('timer',(duration,self.next))
开发者ID:bertsmit,项目名称:pythonclient,代码行数:30,代码来源:CollapseTransition.py

示例10: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class Race:
    def __init__(self):
        self.stageFinishCount = 0
        self.stageStartCount = 0 
        self.mutex = Semaphore(1) #used for mutual exclusion while writing
        self.stageFinishSema = Semaphore(0)
        self.stageStartSema = Semaphore(0) #This is used so that people dont try to finish the next stage until everyone has left the prev stage  
    def teammate_start_stage(self):
        count = 0
        with self.mutex:
            self.stageStartCount = self.stageStartCount + 1
            count = self.stageStartCount

        if count < NUM_TEAMMATES:
            self.stageStartSema.acquire()
        else:
            self.stageStartCount = 0
            for i in range(NUM_TEAMMATES-1):
                self.stageStartSema.release() # only last person starting the stage would release all thread.

    def teammate_finish_stage(self):
        count = 0 #local variable separate to each thread
        with self.mutex:
            self.stageFinishCount = self.stageFinishCount + 1
            count = self.stageFinishCount

        if count < NUM_TEAMMATES:
            self.stageFinishSema.acquire()
        else:
            self.stageFinishCount = 0
            for i in range(NUM_TEAMMATES-1):
                self.stageFinishSema.release() #last teammate only can do this
开发者ID:kathomas921,项目名称:courses,代码行数:34,代码来源:q08.py

示例11: ReusableBarrierSem

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class ReusableBarrierSem():
    def __init__(self, num_threads):
        self.num_threads = num_threads
        self.count_threads1 = self.num_threads
        self.count_threads2 = self.num_threads

        self.counter_lock = Lock()       # protejam decrementarea numarului de threaduri
        self.threads_sem1 = Semaphore(0) # contorizam numarul de threaduri pentru prima etapa
        self.threads_sem2 = Semaphore(0) # contorizam numarul de threaduri pentru a doua etapa

    def wait(self):
        self.phase1()
        self.phase2()

    def phase1(self):
        with self.counter_lock:
            self.count_threads1 -= 1
            if self.count_threads1 == 0:
                for i in range(self.num_threads):
                    self.threads_sem1.release()
            self.count_threads2 = self.num_threads

        self.threads_sem1.acquire()

    def phase2(self):
        with self.counter_lock:
            self.count_threads2 -= 1
            if self.count_threads2 == 0:
                for i in range(self.num_threads):
                    self.threads_sem2.release()
            self.count_threads1 = self.num_threads

        self.threads_sem2.acquire()
开发者ID:cataliniordache,项目名称:Computers-Architecture-Assignments,代码行数:35,代码来源:barrier.py

示例12: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class Synchronized:
	def __init__(self):
		from threading import Semaphore
		self.__lock = Semaphore()
		self.__ownerThread = None
		classdict = self.__class__.__dict__
		for attr in classdict.get("__synchronized__", ()):
			try:
				method = classdict[attr]
				if callable(method):
					self.__dict__[attr] = CallHook(self, method)
				else:
					if VERBOSE: print "! Synchronized: Object is not callable: %s" % (attr,)
			except KeyError:
				if VERBOSE: print "! Synchronized: Method not found: %s" % (attr,)

	def releaseInstance(self):
		self.__ownerThread = None
		self.__lock.release()

	def acquireInstance(self):
		self.__lock.acquire()
		self.__ownerThread = currentThread()

	def ownerThread(self):
		return self.__ownerThread
开发者ID:HarmonyEnterpriseSolutions,项目名称:toolib,代码行数:28,代码来源:Synchronized.py

示例13: __init__

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class LEDManager:
    def __init__(self):
        self.threadStopEvent = Event()
        self.sem = Semaphore()
        self.controlThread = None
        self._cancelPowerOffEvent = None
        self._colorSetter = ColorSetter(1.0)

    def setBrightness(self, brightness):
        self._colorSetter.setBrightness(brightness)

    def getBrightness(self):
        return self._colorSetter.getBrightness()

    def startProgram(self, program):
        self.sem.acquire()
        program.setColorSetter(self._colorSetter)
        if self.controlThread is not None:
            self.controlThread.threadStopEvent.set()
            lastValue = self.controlThread.program.getCurrentValue()
            program.setLastValue(lastValue)
        self.controlThread = LEDControlThread(program)
        self.controlThread.start()
        self.sem.release()

    def getCurrentProgram(self):
        if self.controlThread is not None:
            if self.controlThread.program is not None:
                return self.controlThread.program
        return None

    def getCurrentValue(self):
        if self.controlThread is not None:
            if self.controlThread.program is not None:
                return self.controlThread.program.getCurrentValue()
        return None

    def powerOffWaiter(self, duration, cancelEvent):
        cancelEvent.wait(duration)
        if cancelEvent.is_set():
            logging.getLogger("main").info("canceled power off")
            return
        logging.getLogger("main").info("wait finished starting SoftOffProgram")
        self.startProgram(SmoothNextColorProgram(LEDState(0.0, 0.0, 0.0, 1.0), 1, 3))
        self._cancelPowerOffEvent = None

    def schedulePowerOff(self, duration):
        if self._cancelPowerOffEvent is not None:
            self._cancelPowerOffEvent.set()
        self._cancelPowerOffEvent = Event()
        t = Thread(target=self.powerOffWaiter, args=(duration, self._cancelPowerOffEvent))
        t.start()

    def cancelPowerOff(self):
        if self._cancelPowerOffEvent is not None:
            self._cancelPowerOffEvent.set()
            self._cancelPowerOffEvent = None

    def isPowerOffScheduled(self):
        return self._cancelPowerOffEvent is not None
开发者ID:s0riak,项目名称:pi-led-control,代码行数:62,代码来源:ledmanager.py

示例14: IterableThread

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class IterableThread(Thread):
    def __init__(self, storage_object):
        Thread.__init__(self)
        self.data = ''
        self.storage_object = storage_object
        self.notstarted = True
        self.semaphore = Semaphore()
        self.closed = False

    def read(self, size):
        while len(self.data) < size and not self.closed:
            self.semaphore.acquire(True)
        ret = self.data[:size]
        self.data = self.data[size:]
        return ret

    def write(self, data):
        self.data += data
        if not self.isAlive(): self.start()
        self.semaphore.release()

    def run(self):
        self.storage_object.send(self)

    def close(self):
        self.closed = True
        self.semaphore.release()
开发者ID:meeuw,项目名称:cfbrowser,代码行数:29,代码来源:ftpserver.py

示例15: AsyncWorker

# 需要导入模块: from threading import Semaphore [as 别名]
# 或者: from threading.Semaphore import release [as 别名]
class AsyncWorker(object):

    def __init__(self, view):
        self.view = view
        self.plugin = get_plugin(view)
        self.content = view.substr(sublime.Region(0, view.size()))
        self.filename = view.file_name()
        self.view_id = view.buffer_id()
        self.errors = None
        self.sem = Semaphore()
        self.sem.acquire()
        self.has_round_queued = False

    def do_more_work(self):
        self.content = self.view.substr(sublime.Region(0, self.view.size()))
        if not self.has_round_queued:
            self.sem.release()
            self.has_round_queued = True

    def final(self):
        self.plugin.handle_errors(self.view, self.errors)
        self.plugin.set_error_status(self.view)
        self.has_round_queued = False

    def work(self):
        while True:
            # Wait on semaphore
            self.sem.acquire()
            # Update the script
            self.plugin.update_server_code(self.filename, self.content)
            # Get errors
            self.errors = self.plugin.serv_get_errors(self.filename)
            sublime.set_timeout(self.final, 1)
            self.content = self.plugin.views_text[self.filename]
            sleep(1.3)
开发者ID:Diullei,项目名称:sublime-typescript,代码行数:37,代码来源:typescript.py


注:本文中的threading.Semaphore.release方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。