day9--多线程与多进程
线程:
什么是线程?
线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务
每一个程序的内存是独立的,互相不能直接访问。
进程:
以一个整体的形式暴露给操作系统管理,里面包含对各种资源的调用,内存的对各种资源管理的集合就可以称为进程。进程本身是不可以执行的,只是一堆指令,操作系统是线程执行的。
表面看进程在执行,其实是线程在执行,一个进程至少包含一个线程。
线程:线程就是可执行的上下文,CPU执行所需要的最小单位。CPU只负责运算。单核的CPU同时只能做一件事情,为什么我们可以切换各种程序,是由于CPU的执行速度很快,在来回切换,让我们看起来程序是执行多个进程。
操作系统通过PID,进程ID来区分进程。进程标识符,PID。进程能够设置优先级。
线程是有主线程创建的,primary thread;能够一直创建新的线程,Linux操作系统有一个主线程。
线程和进程的区别:
线程和进程比快是没有可比性的。
1、线程共享内存空间,进程的内存是独立的;
2、同一个进程的线程之间可以直接交流,两个进程想通信,必须通过一个中间代理来实现;
3、新的线程容易创建,创建新线程需要对其父进程进行一次克隆;(parent process)
4、一个线程可以控制和操作同一进程里的其他线程,但是进程只能操作子进程;
5、线程之间数据可以交流,进程之间是不允许数据交流的。
线程源代码:
"""Thread module emulating a subset of Java's threading model.""" import sys as _sys import _thread from time import monotonic as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice, count as _count try: from _collections import deque as _deque except ImportError: from collections import deque as _deque # Note regarding PEP 8 compliant names # This threading model was originally inspired by Java, and inherited # the convention of camelCase function and method names from that # language. Those original names are not in any imminent danger of # being deprecated (even for Py3k),so this module provides them as an # alias for the PEP 8 compliant names # Note that using the new PEP 8 compliant names facilitates substitution # with the multiprocessing module, which doesn't provide the old # Java inspired names. __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'] # Rename some stuff so "from threading import *" is safe _start_new_thread = _thread.start_new_thread _allocate_lock = _thread.allocate_lock _set_sentinel = _thread._set_sentinel get_ident = _thread.get_ident ThreadError = _thread.error try: _CRLock = _thread.RLock except AttributeError: _CRLock = None TIMEOUT_MAX = _thread.TIMEOUT_MAX del _thread # Support for profile and trace hooks _profile_hook = None _trace_hook = None def setprofile(func): """Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called. """ global _profile_hook _profile_hook = func def settrace(func): """Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called. """ global _trace_hook _trace_hook = func # Synchronization classes Lock = _allocate_lock def RLock(*args, **kwargs): """Factory function that returns a new reentrant lock. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. """ if _CRLock is None: return _PyRLock(*args, **kwargs) return _CRLock(*args, **kwargs) class _RLock: """This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. """ def __init__(self): self._block = _allocate_lock() self._owner = None self._count = 0 def __repr__(self): owner = self._owner try: owner = _active[owner].name except KeyError: pass return "<%s %s.%s object owner=%r count=%d at %s>" % ( "locked" if self._block.locked() else "unlocked", self.__class__.__module__, self.__class__.__qualname__, owner, self._count, hex(id(self)) ) def acquire(self, blocking=True, timeout=-1): """Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return true. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return true if the lock has been acquired, false if the timeout has elapsed. """ me = get_ident() if self._owner == me: self._count += 1 return 1 rc = self._block.acquire(blocking, timeout) if rc: self._owner = me self._count = 1 return rc __enter__ = acquire def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. """ if self._owner != get_ident(): raise RuntimeError("cannot release un-acquired lock") self._count = count = self._count - 1 if not count: self._owner = None self._block.release() def __exit__(self, t, v, tb): self.release() # Internal methods used by condition variables def _acquire_restore(self, state): self._block.acquire() self._count, self._owner = state def _release_save(self): if self._count == 0: raise RuntimeError("cannot release un-acquired lock") count = self._count self._count = 0 owner = self._owner self._owner = None self._block.release() return (count, owner) def _is_owned(self): return self._owner == get_ident() _PyRLock = _RLock class Condition: """Class that implements a condition variable. A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock. """ def __init__(self, lock=None): if lock is None: lock = RLock() self._lock = lock # Export the lock's acquire() and release() methods self.acquire = lock.acquire self.release = lock.release # If the lock defines _release_save() and/or _acquire_restore(), # these override the default implementations (which just call # release() and acquire() on the lock). Ditto for _is_owned(). try: self._release_save = lock._release_save except AttributeError: pass try: self._acquire_restore = lock._acquire_restore except AttributeError: pass try: self._is_owned = lock._is_owned except AttributeError: pass self._waiters = _deque() def __enter__(self): return self._lock.__enter__() def __exit__(self, *args): return self._lock.__exit__(*args) def __repr__(self): return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) def _release_save(self): self._lock.release() # No state to save def _acquire_restore(self, x): self._lock.acquire() # Ignore saved state def _is_owned(self): # Return True if lock is owned by current_thread. # This method is called only if _lock doesn't have _is_owned(). if self._lock.acquire(0): self._lock.release() return False else: return True def wait(self, timeout=None): """Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. Another internal interface is then used to restore the recursion level when the lock is reacquired. """ if not self._is_owned(): raise RuntimeError("cannot wait on un-acquired lock") waiter = _allocate_lock() waiter.acquire() self._waiters.append(waiter) saved_state = self._release_save() gotit = False try: # restore state no matter what (e.g., KeyboardInterrupt) if timeout is None: waiter.acquire() gotit = True else: if timeout > 0: gotit = waiter.acquire(True, timeout) else: gotit = waiter.acquire(False) return gotit finally: self._acquire_restore(saved_state) if not gotit: try: self._waiters.remove(waiter) except ValueError: pass def wait_for(self, predicate, timeout=None): """Wait until a condition evaluates to True. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait. """ endtime = None waittime = timeout result = predicate() while not result: if waittime is not None: if endtime is None: endtime = _time() + waittime else: waittime = endtime - _time() if waittime <= 0: break self.wait(waittime) result = predicate() return result def notify(self, n=1): """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting. """ if not self._is_owned(): raise RuntimeError("cannot notify on un-acquired lock") all_waiters = self._waiters waiters_to_notify = _deque(_islice(all_waiters, n)) if not waiters_to_notify: return for waiter in waiters_to_notify: waiter.release() try: all_waiters.remove(waiter) except ValueError: pass def notify_all(self): """Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. """ self.notify(len(self._waiters)) notifyAll = notify_all class Semaphore: """This class implements semaphore objects. Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ # After Tim Peters' semaphore class, but not quite the same (no maximum) def __init__(self, value=1): if value < 0: raise ValueError("semaphore initial value must be >= 0") self._cond = Condition(Lock()) self._value = value def acquire(self, blocking=True, timeout=None): """Acquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero on entry, block, waiting until some other thread has called release() to make it larger than zero. This is done with proper interlocking so that if multiple acquire() calls are blocked, release() will wake exactly one of them up. The implementation may pick one at random, so the order in which blocked threads are awakened should not be relied on. There is no return value in this case. When invoked with blocking set to true, do the same thing as when called without arguments, and return true. When invoked with blocking set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return false. Return true otherwise. """ if not blocking and timeout is not None: raise ValueError("can't specify timeout for non-blocking acquire") rc = False endtime = None with self._cond: while self._value == 0: if not blocking: break if timeout is not None: if endtime is None: endtime = _time() + timeout else: timeout = endtime - _time() if timeout <= 0: break self._cond.wait(timeout) else: self._value -= 1 rc = True return rc __enter__ = acquire def release(self): """Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. """ with self._cond: self._value += 1 self._cond.notify() def __exit__(self, t, v, tb): self.release() class BoundedSemaphore(Semaphore): """Implements a bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1. Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ def __init__(self, value=1): Semaphore.__init__(self, value) self._initial_value = value def release(self): """Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. If the number of releases exceeds the number of acquires, raise a ValueError. """ with self._cond: if self._value >= self._initial_value: raise ValueError("Semaphore released too many times") self._value += 1 self._cond.notify() class Event: """Class implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. """ # After Tim Peters' event class (without is_posted()) def __init__(self): self._cond = Condition(Lock()) self._flag = False def _reset_internal_locks(self): # private! called by Thread._reset_internal_locks by _after_fork() self._cond.__init__(Lock()) def is_set(self): """Return true if and only if the internal flag is true.""" return self._flag isSet = is_set def set(self): """Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ with self._cond: self._flag = True self._cond.notify_all() def clear(self): """Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again. """ with self._cond: self._flag = False def wait(self, timeout=None): """Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out. """ with self._cond: signaled = self._flag if not signaled: signaled = self._cond.wait(timeout) return signaled # A barrier class. Inspired in part by the pthread_barrier_* api and # the CyclicBarrier class from Java. See # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ # CyclicBarrier.html # for information. # We maintain two main states, 'filling' and 'draining' enabling the barrier # to be cyclic. Threads are not allowed into it until it has fully drained # since the previous cycle. In addition, a 'resetting' state exists which is # similar to 'draining' except that threads leave with a BrokenBarrierError, # and a 'broken' state in which all threads get the exception. class Barrier: """Implements a Barrier. Useful for synchronizing a fixed number of threads at known synchronization points. Threads block on 'wait()' and are simultaneously once they have all made that call. """ def __init__(self, parties, action=None, timeout=None): """Create a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to releasing them all. If a 'timeout' is provided, it is uses as the default for all subsequent 'wait()' calls. """ self._cond = Condition(Lock()) self._action = action self._timeout = timeout self._parties = parties self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken self._count = 0 def wait(self, timeout=None): """Wait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties-1'. """ if timeout is None: timeout = self._timeout with self._cond: self._enter() # Block while the barrier drains. index = self._count self._count += 1 try: if index + 1 == self._parties: # We release the barrier self._release() else: # We wait until someone releases us self._wait(timeout) return index finally: self._count -= 1 # Wake up any threads waiting for barrier to drain. self._exit() # Block until the barrier is ready for us, or raise an exception # if it is broken. def _enter(self): while self._state in (-1, 1): # It is draining or resetting, wait until done self._cond.wait() #see if the barrier is in a broken state if self._state < 0: raise BrokenBarrierError assert self._state == 0 # Optionally run the 'action' and release the threads waiting # in the barrier. def _release(self): try: if self._action: self._action() # enter draining state self._state = 1 self._cond.notify_all() except: #an exception during the _action handler. Break and reraise self._break() raise # Wait in the barrier until we are relased. Raise an exception # if the barrier is reset or broken. def _wait(self, timeout): if not self._cond.wait_for(lambda : self._state != 0, timeout): #timed out. Break the barrier self._break() raise BrokenBarrierError if self._state < 0: raise BrokenBarrierError assert self._state == 1 # If we are the last thread to exit the barrier, signal any threads # waiting for the barrier to drain. def _exit(self): if self._count == 0: if self._state in (-1, 1): #resetting or draining self._state = 0 self._cond.notify_all() def reset(self): """Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. """ with self._cond: if self._count > 0: if self._state == 0: #reset the barrier, waking up threads self._state = -1 elif self._state == -2: #was broken, set it to reset state #which clears when the last thread exits self._state = -1 else: self._state = 0 self._cond.notify_all() def abort(self): """Place the barrier into a 'broken' state. Useful in case of error. Any currently waiting threads and threads attempting to 'wait()' will have BrokenBarrierError raised. """ with self._cond: self._break() def _break(self): # An internal error was detected. The barrier is set to # a broken state all parties awakened. self._state = -2 self._cond.notify_all() @property def parties(self): """Return the number of threads required to trip the barrier.""" return self._parties @property def n_waiting(self): """Return the number of threads currently waiting at the barrier.""" # We don't need synchronization here since this is an ephemeral result # anyway. It returns the correct value in the steady state. if self._state == 0: return self._count return 0 @property def broken(self): """Return True if the barrier is in a broken state.""" return self._state == -2 # exception raised by the Barrier class class BrokenBarrierError(RuntimeError): pass # Helper to generate new thread names _counter = _count().__next__ _counter() # Consume 0 so first non-main thread has id 1. def _newname(template="Thread-%d"): return template % _counter() # Active thread administration _active_limbo_lock = _allocate_lock() _active = {} # maps thread id to Thread object _limbo = {} _dangling = WeakSet() # Main class for threads class Thread: """A class that represents a thread of control. This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. """ _initialized = False # Need to store a reference to sys.exc_info for printing # out exceptions when a thread tries to use a global var. during interp. # shutdown and thus raises an exception about trying to perform some # operation on/with a NoneType _exc_info = _sys.exc_info # Keep sys.exc_clear too to clear the exception just before # allowing .join() to return. #XXX __exc_clear = _sys.exc_clear def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): """This constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. *target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. *name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. *args* is the argument tuple for the target invocation. Defaults to (). *kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. """ assert group is None, "group argument must be None for now" if kwargs is None: kwargs = {} self._target = target self._name = str(name or _newname()) self._args = args self._kwargs = kwargs if daemon is not None: self._daemonic = daemon else: self._daemonic = current_thread().daemon self._ident = None self._tstate_lock = None self._started = Event() self._is_stopped = False self._initialized = True # sys.stderr is not stored in the class like # sys.exc_info since it can be changed between instances self._stderr = _sys.stderr # For debugging and _after_fork() _dangling.add(self) def _reset_internal_locks(self, is_alive): # private! Called by _after_fork() to reset our internal locks as # they may be in an invalid state leading to a deadlock or crash. self._started._reset_internal_locks() if is_alive: self._set_tstate_lock() else: # The thread isn't alive after fork: it doesn't have a tstate # anymore. self._is_stopped = True self._tstate_lock = None def __repr__(self): assert self._initialized, "Thread.__init__() was not called" status = "initial" if self._started.is_set(): status = "started" self.is_alive() # easy way to get ._is_stopped set when appropriate if self._is_stopped: status = "stopped" if self._daemonic: status += " daemon" if self._ident is not None: status += " %s" % self._ident return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError("thread.__init__() not called") if self._started.is_set(): raise RuntimeError("threads can only be started once") with _active_limbo_lock: _limbo[self] = self try: _start_new_thread(self._bootstrap, ()) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait() def run(self): """Method representing the thread's activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. """ try: if self._target: self._target(*self._args, **self._kwargs) finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self._target, self._args, self._kwargs def _bootstrap(self): # Wrapper around the real bootstrap code that ignores # exceptions during interpreter cleanup. Those typically # happen when a daemon thread wakes up at an unfortunate # moment, finds the world around it destroyed, and raises some # random exception *** while trying to report the exception in # _bootstrap_inner() below ***. Those random exceptions # don't help anybody, and they confuse users, so we suppress # them. We suppress them only when it appears that the world # indeed has already been destroyed, so that exceptions in # _bootstrap_inner() during normal business hours are properly # reported. Also, we only suppress them for daemonic threads; # if a non-daemonic encounters this, something else is wrong. try: self._bootstrap_inner() except: if self._daemonic and _sys is None: return raise def _set_ident(self): self._ident = get_ident() def _set_tstate_lock(self): """ Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted. """ self._tstate_lock = _set_sentinel() self._tstate_lock.acquire() def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) try: self.run() except SystemExit: pass except: # If sys.stderr is no more (most likely from interpreter # shutdown) use self._stderr. Otherwise still use sys (as in # _sys) in case sys.stderr was redefined since the creation of # self. if _sys and _sys.stderr is not None: print("Exception in thread %s:\n%s" % (self.name, _format_exc()), file=_sys.stderr) elif self._stderr is not None: # Do the best job possible w/o a huge amt. of code to # approximate a traceback (code ideas from # Lib/traceback.py) exc_type, exc_value, exc_tb = self._exc_info() try: print(( "Exception in thread " + self.name + " (most likely raised during interpreter shutdown):"), file=self._stderr) print(( "Traceback (most recent call last):"), file=self._stderr) while exc_tb: print(( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)), file=self._stderr) exc_tb = exc_tb.tb_next print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: del exc_type, exc_value, exc_tb finally: # Prevent a race in # test_threading.test_no_refcycle_through_target when # the exception keeps the target alive past when we # assert that it's dead. #XXX self._exc_clear() pass finally: with _active_limbo_lock: try: # We don't call self._delete() because it also # grabs _active_limbo_lock. del _active[get_ident()] except: pass def _stop(self): # After calling ._stop(), .is_alive() returns False and .join() returns # immediately. ._tstate_lock must be released before calling ._stop(). # # Normal case: C code at the end of the thread's life # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and # that's detected by our ._wait_for_tstate_lock(), called by .join() # and .is_alive(). Any number of threads _may_ call ._stop() # simultaneously (for example, if multiple threads are blocked in # .join() calls), and they're not serialized. That's harmless - # they'll just make redundant rebindings of ._is_stopped and # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the # "assert self._is_stopped" in ._wait_for_tstate_lock() always works # (the assert is executed only if ._tstate_lock is None). # # Special case: _main_thread releases ._tstate_lock via this # module's _shutdown() function. lock = self._tstate_lock if lock is not None: assert not lock.locked() self._is_stopped = True self._tstate_lock = None def _delete(self): "Remove current thread from the dict of currently running threads." # Notes about running with _dummy_thread: # # Must take care to not raise an exception if _dummy_thread is being # used (and thus this module is being used as an instance of # dummy_threading). _dummy_thread.get_ident() always returns -1 since # there is only one thread if _dummy_thread is being used. Thus # len(_active) is always <= 1 here, and any Thread instance created # overwrites the (if any) thread currently registered in _active. # # An instance of _MainThread is always created by 'threading'. This # gets overwritten the instant an instance of Thread is created; both # threads return -1 from _dummy_thread.get_ident() and thus have the # same key in the dict. So when the _MainThread instance created by # 'threading' tries to clean itself up when atexit calls this method # it gets a KeyError if another Thread instance was created. # # This all means that KeyError from trying to delete something from # _active if dummy_threading is being used is a red herring. But # since it isn't if dummy_threading is *not* being used then don't # hide the exception. try: with _active_limbo_lock: del _active[get_ident()] # There must not be any python code between the previous line # and after the lock is released. Otherwise a tracing function # could try to acquire the lock again in the same thread, (in # current_thread()), and would block. except KeyError: if 'dummy_threading' not in _sys.modules: raise def join(self, timeout=None): """Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception. """ if not self._initialized: raise RuntimeError("Thread.__init__() not called") if not self._started.is_set(): raise RuntimeError("cannot join thread before it is started") if self is current_thread(): raise RuntimeError("cannot join current thread") if timeout is None: self._wait_for_tstate_lock() else: # the behavior of a negative timeout isn't documented, but # historically .join(timeout=x) for x<0 has acted as if timeout=0 self._wait_for_tstate_lock(timeout=max(timeout, 0)) def _wait_for_tstate_lock(self, block=True, timeout=-1): # Issue #18808: wait for the thread state to be gone. # At the end of the thread's life, after all knowledge of the thread # is removed from C data structures, C code releases our _tstate_lock. # This method passes its arguments to _tstate_lock.acquire(). # If the lock is acquired, the C code is done, and self._stop() is # called. That sets ._is_stopped to True, and ._tstate_lock to None. lock = self._tstate_lock if lock is None: # already determined that the C code is done assert self._is_stopped elif lock.acquire(block, timeout): lock.release() self._stop() @property def name(self): """A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. """ assert self._initialized, "Thread.__init__() not called" return self._name @name.setter def name(self, name): assert self._initialized, "Thread.__init__() not called" self._name = str(name) @property def ident(self): """Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the thread.get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. """ assert self._initialized, "Thread.__init__() not called" return self._ident def is_alive(self): """Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. """ assert self._initialized, "Thread.__init__() not called" if self._is_stopped or not self._started.is_set(): return False self._wait_for_tstate_lock(False) return not self._is_stopped isAlive = is_alive @property def daemon(self): """A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left. """ assert self._initialized, "Thread.__init__() not called" return self._daemonic @daemon.setter def daemon(self, daemonic): if not self._initialized: raise RuntimeError("Thread.__init__() not called") if self._started.is_set(): raise RuntimeError("cannot set daemon status of active thread") self._daemonic = daemonic def isDaemon(self): return self.daemon def setDaemon(self, daemonic): self.daemon = daemonic def getName(self): return self.name def setName(self, name): self.name = name # The timer class was contributed by Itamar Shtull-Trauring class Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() # Special thread class to represent the main thread # This is garbage collected through an exit handler class _MainThread(Thread): def __init__(self): Thread.__init__(self, name="MainThread", daemon=False) self._set_tstate_lock() self._started.set() self._set_ident() with _active_limbo_lock: _active[self._ident] = self # Dummy thread class to represent threads not started here. # These aren't garbage collected when they die, nor can they be waited for. # If they invoke anything in threading.py that calls current_thread(), they # leave an entry in the _active dict forever after. # Their purpose is to return *something* from current_thread(). # They are marked as daemon threads so we won't wait for them # when we exit (conform previous semantics). class _DummyThread(Thread): def __init__(self): Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True) self._started.set() self._set_ident() with _active_limbo_lock: _active[self._ident] = self def _stop(self): pass def join(self, timeout=None): assert False, "cannot join a dummy thread" # Global API functions def current_thread(): """Return the current Thread object, corresponding to the caller's thread of control. If the caller's thread of control was not created through the threading module, a dummy thread object with limited functionality is returned. """ try: return _active[get_ident()] except KeyError: return _DummyThread() currentThread = current_thread def active_count(): """Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate(). """ with _active_limbo_lock: return len(_active) + len(_limbo) activeCount = active_count def _enumerate(): # Same as enumerate(), but without the lock. Internal use only. return list(_active.values()) + list(_limbo.values()) def enumerate(): """Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started. """ with _active_limbo_lock: return list(_active.values()) + list(_limbo.values()) from _thread import stack_size # Create the main thread object, # and make it available for the interpreter # (Py_Main) as threading._shutdown. _main_thread = _MainThread() def _shutdown(): # Obscure: other threads may be waiting to join _main_thread. That's # dubious, but some code does it. We can't wait for C code to release # the main thread's tstate_lock - that won't happen until the interpreter # is nearly dead. So we release it here. Note that just calling _stop() # isn't enough: other threads may already be waiting on _tstate_lock. tlock = _main_thread._tstate_lock # The main thread isn't finished yet, so its thread state lock can't have # been released. assert tlock is not None assert tlock.locked() tlock.release() _main_thread._stop() t = _pickSomeNonDaemonThread() while t: t.join() t = _pickSomeNonDaemonThread() _main_thread._delete() def _pickSomeNonDaemonThread(): for t in enumerate(): if not t.daemon and t.is_alive(): return t return None def main_thread(): """Return the main thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. """ return _main_thread # get thread-local implementation, either from the thread # module, or from the python fallback try: from _thread import _local as local except ImportError: from _threading_local import local def _after_fork(): # This function is called by Python/ceval.c:PyEval_ReInitThreads which # is called from PyOS_AfterFork. Here we cleanup threading module state # that should not exist after a fork. # Reset _active_limbo_lock, in case we forked while the lock was held # by another (non-forked) thread. http://bugs.python.org/issue874900 global _active_limbo_lock, _main_thread _active_limbo_lock = _allocate_lock() # fork() only copied the current thread; clear references to others. new_active = {} current = current_thread() _main_thread = current with _active_limbo_lock: # Dangling thread instances must still have their locks reset, # because someone may join() them. threads = set(_enumerate()) threads.update(_dangling) for thread in threads: # Any lock/condition variable may be currently locked or in an # invalid state, so we reinitialize them. if thread is current: # There is only one active thread. We reset the ident to # its new value since it can have changed. thread._reset_internal_locks(True) ident = get_ident() thread._ident = ident new_active[ident] = thread else: # All the others are already stopped. thread._reset_internal_locks(False) thread._stop() _limbo.clear() _active.clear() _active.update(new_active) assert len(_active) == 1
线程实例:
Python threading模块
线程有2种调用方式,如下:
直接调用
import threading,time def func(num): print("The lucky num is ",num) time.sleep(2) if __name__ == "__main__": start_time = time.time() t1 = threading.Thread(target=func,args=(6,)) t2 = threading.Thread(target=func,args=(9,)) t1.start() t2.start() end_time = time.time() run_time = end_time-start_time print("\033[34;1m程序运行时间:\033[0m",run_time) time1 = time.time() func(6) func(9) time2 = time.time() run_time2 = time2 - time1 print("\033[32m直接执行需要时间:\033[0m",run_time2)
执行结果如下:
The lucky num is 6
The lucky num is 9
程序运行时间: 0.00044083595275878906
The lucky num is 6
The lucky num is 9
直接执行需要时间: 4.002933979034424
从上面代码可以看出,我们使用的是线程,threading.Thread,线程里面target=func(函数名),args=(参数,),可以看出,线程的速度很快,启动两个线程执行需要之间很短,但是这只是启动线程的时间,IO操作其实并没有执行,这个时候,程序还没有执行完毕,但是线程是不管的,直接会向下执行,而串行的程序则不一样,一行一行执行,因此运行的时间就是叠加的。
所以上面,第一个时间只是线程启动过程中花费的时间,并没有算IO操作的时间,IO操作等待的时候,线程会向下执行,不会等待程序执行,接着往下运行,只有等到下面也有IO操作的时候,才会看上面是否执行完毕,上面线程执行完毕则打印,但是不管怎样,最后都会等待程序执行完毕,然后才结束程序。
继承式调用
import threading,time class MyThreading(threading.Thread): '''定义一个线程类''' def __init__(self,num): #初始化子类 super(MyThreading,self).__init__() #由于是继承父类threading.Thread,要重写父类,没有继承参数super(子类,self).__init__(继承父类参数) self.num = num def run(self): print("The lucky num is",self.num) time.sleep(2) print("使用类启动线程,本局执行在什么时候!") if __name__ == "__main__": start_time1 = time.time() t1 = MyThreading(6) t2 = MyThreading(9) t1.start() t2.start() end_time1 = time.time() run_time1 = end_time1 - start_time1 print("线程运行时间:",run_time1) start_time2 = time.time() t1.run() t2.run() end_time2 = time.time() run_time2 = end_time2 - start_time2 print("串行程序执行时间:",run_time2)
执行结果如下:
The lucky num is 6
The lucky num is 9
线程运行时间: 0.0004470348358154297
The lucky num is 6
使用类启动线程,本局执行在什么时候!
使用类启动线程,本局执行在什么时候!
使用类启动线程,本局执行在什么时候!
The lucky num is 9
使用类启动线程,本局执行在什么时候!
串行程序执行时间: 4.004571914672852
上面程序是用类写的线程,上面线程是继承threading里面的类Thread,
threading.Thread源代码:
class Thread: """A class that represents a thread of control. This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. """ _initialized = False # Need to store a reference to sys.exc_info for printing # out exceptions when a thread tries to use a global var. during interp. # shutdown and thus raises an exception about trying to perform some # operation on/with a NoneType _exc_info = _sys.exc_info # Keep sys.exc_clear too to clear the exception just before # allowing .join() to return. #XXX __exc_clear = _sys.exc_clear def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): """This constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. *target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. *name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. *args* is the argument tuple for the target invocation. Defaults to (). *kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. """ assert group is None, "group argument must be None for now" if kwargs is None: kwargs = {} self._target = target self._name = str(name or _newname()) self._args = args self._kwargs = kwargs if daemon is not None: self._daemonic = daemon else: self._daemonic = current_thread().daemon self._ident = None self._tstate_lock = None self._started = Event() self._is_stopped = False self._initialized = True # sys.stderr is not stored in the class like # sys.exc_info since it can be changed between instances self._stderr = _sys.stderr # For debugging and _after_fork() _dangling.add(self) def _reset_internal_locks(self, is_alive): # private! Called by _after_fork() to reset our internal locks as # they may be in an invalid state leading to a deadlock or crash. self._started._reset_internal_locks() if is_alive: self._set_tstate_lock() else: # The thread isn't alive after fork: it doesn't have a tstate # anymore. self._is_stopped = True self._tstate_lock = None def __repr__(self): assert self._initialized, "Thread.__init__() was not called" status = "initial" if self._started.is_set(): status = "started" self.is_alive() # easy way to get ._is_stopped set when appropriate if self._is_stopped: status = "stopped" if self._daemonic: status += " daemon" if self._ident is not None: status += " %s" % self._ident return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError("thread.__init__() not called") if self._started.is_set(): raise RuntimeError("threads can only be started once") with _active_limbo_lock: _limbo[self] = self try: _start_new_thread(self._bootstrap, ()) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait() def run(self): """Method representing the thread's activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. """ try: if self._target: self._target(*self._args, **self._kwargs) finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self._target, self._args, self._kwargs def _bootstrap(self): # Wrapper around the real bootstrap code that ignores # exceptions during interpreter cleanup. Those typically # happen when a daemon thread wakes up at an unfortunate # moment, finds the world around it destroyed, and raises some # random exception *** while trying to report the exception in # _bootstrap_inner() below ***. Those random exceptions # don't help anybody, and they confuse users, so we suppress # them. We suppress them only when it appears that the world # indeed has already been destroyed, so that exceptions in # _bootstrap_inner() during normal business hours are properly # reported. Also, we only suppress them for daemonic threads; # if a non-daemonic encounters this, something else is wrong. try: self._bootstrap_inner() except: if self._daemonic and _sys is None: return raise def _set_ident(self): self._ident = get_ident() def _set_tstate_lock(self): """ Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted. """ self._tstate_lock = _set_sentinel() self._tstate_lock.acquire() def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) try: self.run() except SystemExit: pass except: # If sys.stderr is no more (most likely from interpreter # shutdown) use self._stderr. Otherwise still use sys (as in # _sys) in case sys.stderr was redefined since the creation of # self. if _sys and _sys.stderr is not None: print("Exception in thread %s:\n%s" % (self.name, _format_exc()), file=_sys.stderr) elif self._stderr is not None: # Do the best job possible w/o a huge amt. of code to # approximate a traceback (code ideas from # Lib/traceback.py) exc_type, exc_value, exc_tb = self._exc_info() try: print(( "Exception in thread " + self.name + " (most likely raised during interpreter shutdown):"), file=self._stderr) print(( "Traceback (most recent call last):"), file=self._stderr) while exc_tb: print(( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)), file=self._stderr) exc_tb = exc_tb.tb_next print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: del exc_type, exc_value, exc_tb finally: # Prevent a race in # test_threading.test_no_refcycle_through_target when # the exception keeps the target alive past when we # assert that it's dead. #XXX self._exc_clear() pass finally: with _active_limbo_lock: try: # We don't call self._delete() because it also # grabs _active_limbo_lock. del _active[get_ident()] except: pass def _stop(self): # After calling ._stop(), .is_alive() returns False and .join() returns # immediately. ._tstate_lock must be released before calling ._stop(). # # Normal case: C code at the end of the thread's life # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and # that's detected by our ._wait_for_tstate_lock(), called by .join() # and .is_alive(). Any number of threads _may_ call ._stop() # simultaneously (for example, if multiple threads are blocked in # .join() calls), and they're not serialized. That's harmless - # they'll just make redundant rebindings of ._is_stopped and # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the # "assert self._is_stopped" in ._wait_for_tstate_lock() always works # (the assert is executed only if ._tstate_lock is None). # # Special case: _main_thread releases ._tstate_lock via this # module's _shutdown() function. lock = self._tstate_lock if lock is not None: assert not lock.locked() self._is_stopped = True self._tstate_lock = None def _delete(self): "Remove current thread from the dict of currently running threads." # Notes about running with _dummy_thread: # # Must take care to not raise an exception if _dummy_thread is being # used (and thus this module is being used as an instance of # dummy_threading). _dummy_thread.get_ident() always returns -1 since # there is only one thread if _dummy_thread is being used. Thus # len(_active) is always <= 1 here, and any Thread instance created # overwrites the (if any) thread currently registered in _active. # # An instance of _MainThread is always created by 'threading'. This # gets overwritten the instant an instance of Thread is created; both # threads return -1 from _dummy_thread.get_ident() and thus have the # same key in the dict. So when the _MainThread instance created by # 'threading' tries to clean itself up when atexit calls this method # it gets a KeyError if another Thread instance was created. # # This all means that KeyError from trying to delete something from # _active if dummy_threading is being used is a red herring. But # since it isn't if dummy_threading is *not* being used then don't # hide the exception. try: with _active_limbo_lock: del _active[get_ident()] # There must not be any python code between the previous line # and after the lock is released. Otherwise a tracing function # could try to acquire the lock again in the same thread, (in # current_thread()), and would block. except KeyError: if 'dummy_threading' not in _sys.modules: raise def join(self, timeout=None): """Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception. """ if not self._initialized: raise RuntimeError("Thread.__init__() not called") if not self._started.is_set(): raise RuntimeError("cannot join thread before it is started") if self is current_thread(): raise RuntimeError("cannot join current thread") if timeout is None: self._wait_for_tstate_lock() else: # the behavior of a negative timeout isn't documented, but # historically .join(timeout=x) for x<0 has acted as if timeout=0 self._wait_for_tstate_lock(timeout=max(timeout, 0)) def _wait_for_tstate_lock(self, block=True, timeout=-1): # Issue #18808: wait for the thread state to be gone. # At the end of the thread's life, after all knowledge of the thread # is removed from C data structures, C code releases our _tstate_lock. # This method passes its arguments to _tstate_lock.acquire(). # If the lock is acquired, the C code is done, and self._stop() is # called. That sets ._is_stopped to True, and ._tstate_lock to None. lock = self._tstate_lock if lock is None: # already determined that the C code is done assert self._is_stopped elif lock.acquire(block, timeout): lock.release() self._stop() @property def name(self): """A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. """ assert self._initialized, "Thread.__init__() not called" return self._name @name.setter def name(self, name): assert self._initialized, "Thread.__init__() not called" self._name = str(name) @property def ident(self): """Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the thread.get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. """ assert self._initialized, "Thread.__init__() not called" return self._ident def is_alive(self): """Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. """ assert self._initialized, "Thread.__init__() not called" if self._is_stopped or not self._started.is_set(): return False self._wait_for_tstate_lock(False) return not self._is_stopped isAlive = is_alive @property def daemon(self): """A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left. """ assert self._initialized, "Thread.__init__() not called" return self._daemonic @daemon.setter def daemon(self, daemonic): if not self._initialized: raise RuntimeError("Thread.__init__() not called") if self._started.is_set(): raise RuntimeError("cannot set daemon status of active thread") self._daemonic = daemonic def isDaemon(self): return self.daemon def setDaemon(self, daemonic): self.daemon = daemonic def getName(self): return self.name def setName(self, name): self.name = name
线程里面,能够获取线程名字,getName(),也能够自行设置线程名setName(),默认情况下线程名字是:Thread-1,Thread-2;
下面来看一个实例:
import threading,time
def func(num):
print("The lucky num is ",num)
time.sleep(2)
print("线程休眠了!")
if __name__ == "__main__":
start_time = time.time()
for i in range(10):
t1 = threading.Thread(target=func,args=("thread_%s" %i,))
t1.start()
end_time = time.time()
print("------------------all thread is running done-----------------------")
run_time = end_time-start_time
print("\033[34;1m程序运行时间:\033[0m",run_time)
上面的代码执行结果如下:
The lucky num is thread_0
The lucky num is thread_1
The lucky num is thread_2
The lucky num is thread_3
The lucky num is thread_4
The lucky num is thread_5
The lucky num is thread_6
The lucky num is thread_7
The lucky num is thread_8
The lucky num is thread_9
------------------all thread is running done-----------------------
程序运行时间: 0.002081155776977539
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
上面,程序运行时间为什么只有0.00282秒,为什么不是2秒?下面来做细致的分析:
首先一个程序至少有一个线程,程序本身就是主线程,主线程启动子线程,主线程是独立的,子线程也是独立的,两者之间是并行的,主线程和子线程相互独立,是并行的,各自执行各自的,主线程还是继续向下执行,子线程也在独自执行。程序本身就是线程。
下面,我们通过列表,让每个线程自行执行完毕:
import threading,time def func(num): print("The lucky num is ",num) time.sleep(2) print("线程休眠了!") if __name__ == "__main__": start_time = time.time() lists = [] for i in range(10): t = threading.Thread(target=func,args=("thread_%s" %i,)) t.start() lists.append(t) for w in lists: w.join() #join()是让程序执行完毕,我们遍历,让每个线程自行执行完毕 end_time = time.time() print("------------------all thread is running done-----------------------") run_time = end_time-start_time print("\033[34;1m程序运行时间:\033[0m",run_time)
程序执行如下:
The lucky num is thread_0
The lucky num is thread_1
The lucky num is thread_2
The lucky num is thread_3
The lucky num is thread_4
The lucky num is thread_5
The lucky num is thread_6
The lucky num is thread_7
The lucky num is thread_8
The lucky num is thread_9
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
线程休眠了!
------------------all thread is running done-----------------------
程序运行时间: 2.0065605640411377
上面程序中,我们加入了一个列表,让每个线程启动之后,放入一个列表中,然后遍历列表,让每个线程都执行完毕再执行下面的程序。
可以看出,所有线程执行完毕花费的总时间是:2.0065605640411377,这就是所有线程执行的时间。创建临时列表,让程序执行之后,每个线程各自执行,不影响其他线程,否则就是串行的。
join()解释:"""Wait until the thread terminates.等待线程终止(结束)
上面程序中,我们启动了10个线程,那么第一个启动的线程是否是主线程呢?不是的,主线程是程序本身,我们启动程序的时候,程序是由上而下执行的,本身就是一个线程,这个线程就是主线程,也即程序本身,下面我们来验证一下:
import threading,time def func(num): print("The lucky num is ",num) time.sleep(2) print("线程休眠了!,什么线程?",threading.current_thread()) if __name__ == "__main__": start_time = time.time() lists = [] for i in range(10): t = threading.Thread(target=func,args=("thread_%s" %i,)) t.start() lists.append(t) print("\033[31m运行的线程数:%s\033[0m" % threading.active_count()) for w in lists: w.join() #join()是让程序执行完毕,我们遍历,让每个线程自行执行完毕 end_time = time.time() print("------------------all thread is running done-----------------------",threading.current_thread()) print("当前运行的线程数:",threading.active_count()) run_time = end_time-start_time print("\033[34;1m程序运行时间:\033[0m",run_time)
上面程序中,我们加入了验证当前线程是否是主线程,在函数和主程序里面我们都加入了验证,并且在线程未结束和结束后加入了统计线程运行的个数,程序运行结果如下:
The lucky num is thread_0 The lucky num is thread_1 The lucky num is thread_2 The lucky num is thread_3 The lucky num is thread_4 The lucky num is thread_5 The lucky num is thread_6 The lucky num is thread_7 The lucky num is thread_8 The lucky num is thread_9 运行的线程数:11 线程休眠了!,什么线程? <Thread(Thread-2, started 140013432059648)> 线程休眠了!,什么线程? <Thread(Thread-1, started 140013440452352)> 线程休眠了!,什么线程? <Thread(Thread-3, started 140013423666944)> 线程休眠了!,什么线程? <Thread(Thread-4, started 140013415274240)> 线程休眠了!,什么线程? <Thread(Thread-10, started 140013022988032)> 线程休眠了!,什么线程? <Thread(Thread-7, started 140013048166144)> 线程休眠了!,什么线程? <Thread(Thread-5, started 140013406881536)> 线程休眠了!,什么线程? <Thread(Thread-6, started 140013398488832)> 线程休眠了!,什么线程? <Thread(Thread-8, started 140013039773440)> 线程休眠了!,什么线程? <Thread(Thread-9, started 140013031380736)> ------------------all thread is running done----------------------- <_MainThread(MainThread, started 140013466183424)> 当前运行的线程数: 1 程序运行时间: 2.0047178268432617
从上面程序的运行结果可以看出,在10个线程启动后,程序是由11个线程在运行,并且启动的线程只是单纯的线程(Thread),而下面线程执行完毕之后,运行的才是主线程<MainThread>;由此可以看出,程序本身才是主线程,启动程序本身,就开启了一个线程,当启动的线程结束后,就会自动停止运行,被杀死,这点和Windows有点区别,在Windows上面,线程还是在激活中。
threading.current_thread()是查看当前线程是否是主线程,threading.active_count()统计当前运行线程的个数。
守护线程:主线程结束之后,其他线程都停止运行,不管其他线程是否执行完毕。帮忙管理资源。
我们知道,如果没有join()主线程会一直执行下去,不管其他线程是否执行完毕,但是最后都在等待其他线程执行完毕之后才结束主线程。把线程转换为守护线程,那么主程序就不会管守护线程是否执行完毕,只需让其他线程执行完毕即可。
下面我们把线程设置为守护线程,如下:
import threading,time def func(num): print("The lucky num is ",num) time.sleep(2) print("线程休眠了!,什么线程?",threading.current_thread()) if __name__ == "__main__": start_time = time.time() lists = [] for i in range(10): t = threading.Thread(target=func,args=("thread_%s" %i,)) t.setDaemon(True) #Daemon:守护进程,把线程设置为守护线程 t.start() lists.append(t) print("\033[31m运行的线程数:%s\033[0m" % threading.active_count()) print("当前执行线程:%s" %threading.current_thread()) # for w in lists: # w.join() #join()是让程序执行完毕,我们遍历,让每个线程自行执行完毕 end_time = time.time() print("------------------all thread is running done-----------------------",threading.current_thread()) print("当前运行的线程数:",threading.active_count()) run_time = end_time-start_time print("\033[34;1m程序运行时间:\033[0m",run_time)
上面程序中,我们启动了10个线程,并将其设置为守护线程,setDaemon(True),下面我们来看看程序的执行情况:
The lucky num is thread_0 The lucky num is thread_1 The lucky num is thread_2 The lucky num is thread_3 The lucky num is thread_4 The lucky num is thread_5 The lucky num is thread_6 The lucky num is thread_7 The lucky num is thread_8 The lucky num is thread_9 运行的线程数:11 当前执行线程:<_MainThread(MainThread, started 140558033020672)> ------------------all thread is running done----------------------- <_MainThread(MainThread, started 140558033020672)> 当前运行的线程数: 11 程序运行时间: 0.0032095909118652344
从程序的执行结果可以看出,当我们把启动的线程设置为守护线程之后,由于遇到IO操作,在守护线程等待的过程中,主程序已经执行完毕了,由于是守护线程,无关紧要,程序结束,不管其是否执行完毕,可以看出,当被设置为守护线程之后,就自己在系统中运行,如果在主程序执行完毕之前执行完毕,则会打印结果,否则主线程关闭,守护线程一起关闭。
setDaemon():是把当前线程设置为守护线程。要在t.start()线程启动之前。
GIL(全局解释器锁)四核机器可以同时做4件事情,单核永远是串行的,四核CPU统一时间真真正正就有四件事情在执行,但是在Python中,无论是4核,8核,统一时间执行的线程都只有一个,这是Python开发时候的一个缺陷,都是单核。Python计算的时候,Python解释器调用的是C语言的接口,只能等待接口返回的结果,不能控制C语言的线程。统一时间只有一个线程能够接收,修改数据。其他语言都是自己写的线程。Python是调用C语言的线程。
线程锁(互斥锁Mutex)
一个进程下可以启动多个线程,多个线程共享父进程的内存空间,也就意味着每个线程可以访问同一份数据,此时,如果2个线程同时要修改同一份数据,会出现什么状况?
正常来讲,这个num结果应该是0,但在python2.7上多运行几次,会发现,最后打印出来的num结果不总是0,为什么每次运行结果不一样呢?哈哈,很简单,假设您有A,B两个线程,此时都要对num进行减1操作,由于2个线程是并发同时运行的,所以2个线程很有可能同时拿走了num=100这个初始变量交给CPU去运算,当A线程去处理完结果是99,但此时B线程运算完的结果也是99,两个线程同时CPU运算的结果赋值给num变量后,结果就都是99。那么怎么办呢?很简单,每个线程在要修改公共数据时,为了避免自己在还没改完的时候别人也来修改此数据,可以给这个数据加一把锁,这样其他线程想修改此数据时就必须等待您修改完毕并把锁释放之后才能再访问此数据。
注:不要在3.x上运行,不知为什么,3.x上的结果总是正确的,可能是自动加了锁。
线程之间是可以互相沟通的,现在下面来看一个例子,所有的线程来修改同一份数据,如下:
import threading,time def func(n): global num time.sleep(0.8) #sleep()是不占用CPU的CPU会执行其他的 num += 1 #所有的线程共同修改num数据 if __name__ == "__main__": num = 0 lists = [] for i in range(1000): t = threading.Thread(target=func,args=("thread_%s" %i,)) # t.setDaemon(True) #Daemon:守护进程,把线程设置为守护线程 t.start() lists.append(t) print("\033[31m运行的线程数:%s\033[0m" % threading.active_count()) for w in lists: w.join() #join()是让程序执行完毕,我们遍历,让每个线程自行执行完毕 print("------------------all thread is running done-----------------------") print("当前运行的线程数:",threading.active_count()) print("num:",num) #所有的线程共同修改一个数据
上面程序中,所有线程都会操作num,让num数量加1,正常结果就是1000,运行结果如下:
运行的线程数:1001 ------------------all thread is running done----------------------- 当前运行的线程数: 1 num: 1000
运行结果也是1000,但是在早期版本中,经常会出现结果不是1000,而是999等接近的数,有些系统运行总是会出现,在Python3中不会有问题,为什么会出现这种情况呢?
解释器同时只放行一个线程运行,申请python解释器锁,执行时间到了,没有执行完毕,由于线程执行是由时间分配,如果执行时间到了,就释放全局解释器锁(gil lock),出现的原因就是由于自己没有执行完毕,就要释放gil lock,没有返回;使此线程虽然执行了,但是没有执行完毕,别的线程拿到的初始值还是没有修改的初始值。
如何解决这个问题呢?要进行加锁,全局解释器(GIL LOCK)自己会加锁和释放锁;我们也自己给程序加锁,释放锁,让程序执行的时候,只有这个线程在执行计算,不会因为Python的GIL LOCK释放,而程序没有执行完毕,出现计算错误;我们自己加锁就是让线程执行完毕之后在释放锁。让其他线程调用。如下:
import threading,time def func(n): lock.acquire() #给线程解锁,让此线程执行完毕 global num # time.sleep(0) #sleep()是不占用CPU的CPU会执行其他的 num += 1 #所有的线程共同修改num数据 lock.release() if __name__ == "__main__": lock = threading.Lock() #声明一个锁的变量 num = 0 lists = [] for i in range(10): t = threading.Thread(target=func,args=("thread_%s" %i,)) # t.setDaemon(True) #Daemon:守护进程,把线程设置为守护线程 t.start() lists.append(t) print("\033[31m运行的线程数:%s\033[0m" % threading.active_count()) for w in lists: w.join() #join()是让程序执行完毕,我们遍历,让每个线程自行执行完毕 print("------------------all thread is running done-----------------------") print("当前运行的线程数:",threading.active_count()) print("num:",num) #所有的线程共同修改一个数据
上面程序中,我们首先声明了一把锁,lock=threading.Lock(),然后在执行线程中加锁,lock.acquire(),最后释放lock.release(),如果加锁的话,一定要记住,程序执行时间比较端,由于释放锁别人才能使用,等于让程序编程串行的了,因而,里面不能有IO操作,不能会执行很慢,加锁让程序效率肯定会变慢,但是确保了数据的准确性。加锁是让本次线程执行完毕才释放,因此之后本次释放才会执行下一次线程。
上面程序中,程序本身执行的时候,GIL LOCK会在系统申请锁,我们自己给程序也加了锁。
递归锁:如果加锁过去,会让程序不知道怎么释放,锁死程序,因而要使用递归锁,程序如下:
import threading '''自己写一个递归所的实例''' def run1(num): lock.acquire() num += 1 lock.release() return num def run2(num): lock.acquire() num += 2 lock.release() return num def run3(x,y): lock.acquire() """执行run1""" res1 = run1(x) #调用run1,run1里面也加锁了,是run3下面的锁 '''执行run2''' res2 = run2(y) #调用run2,run2里面也加锁了,是run3下面的锁,与run1平行,没有上下级关系 lock.release() print("res1:",res1,"res2:",res2) if __name__ == "__main__": lock = threading.Lock() for i in range(10): t = threading.Thread(target=run3,args=(1,1,)) #对run3函数加锁 t.start() while threading.active_count() != 1: #判断活跃线程个数,当其他线程都执行完毕,只剩主线程时,就是1 print("\033[31m活跃的线程个数:%s\033[0m" %threading.active_count()) else: print("All the threading task done!!!")
上面,我们写了三个函数,函数run3中调用run1和run2,run3里面加锁,并且run1和run2也加锁了,run1和run2是run3下面的锁,run1和run2是平行锁,两者不存在上下级关系,现在我们来执行程序,看是什么样的结果,如下:
活跃的线程个数:11 活跃的线程个数:11 活跃的线程个数:11 活跃的线程个数:11 活跃的线程个数:11 活跃的线程个数:11 活跃的线程个数:11 活跃的线程个数:11 ......
从上面执行结果可以看出,并没有执行启动的10个线程,由于每层都加锁,导致程序识别锁混乱,如何结果呢?要使用到递归锁,何为递归所呢,就是给自己加上标记。
import threading '''写一个递归锁''' def run1(): lock.acquire() #加锁 global num1 num1 += 1 lock.release() return num1 def run2(): '''加锁''' lock.acquire() global num2 num2 += 2 lock.release() return num2 def run3(): lock.acquire() res1 = run1() '''执行第二个调用''' res2 = run2() lock.release() print(res1,res2) if __name__ == "__main__": num1,num2 =1,2 lock = threading.RLock() for i in range(10): t = threading.Thread(target=run3) t.start() while threading.active_count() != 1: print("\033[31m当前活跃的线程个数:%s\033[0m" %threading.active_count()) else: print("All the thread has task done!!!!") print(num1,num2)
上面代码中,我们进行了修改,使用了递归锁,即有明确的出口,递归:recursion,这样,就解决了问题,如下:
2 4 3 6 4 8 5 10 6 12 7 14 8 16 9 18 10 20 11 22 当前活跃的线程个数:2 All the thread has task done!!!! 11 22
上面程序中,结果能够正确的运行,并且嵌套锁没有出错,是因为使用了递归锁RLock(),从上面程序中,我也简单掌握了全局变量的使用,在函数中如何修改全局变量,首先定义一个全局变量,然后修改即可。
Semaphore(信号量)
互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。
互斥锁:控制线程同一时间执行的数量,我们可以启动多个线程,但是我们可以规定统一时间让几个线程执行,当有线程执行完毕之后,添加新的线程进去,直至所有线程执行完毕。
import threading,time '''写一个递归锁''' def run1(): global num1 num1 += 1 return num1 def run2(): global num2 num2 += 2 return num2 def run3(): semaphore.acquire() res1 = run1() '''执行第二个调用''' res2 = run2() semaphore.release() time.sleep(2) print(res1,res2) if __name__ == "__main__": num1,num2 =1,2 lock = threading.RLock() semaphore = threading.BoundedSemaphore(5) for i in range(10): t = threading.Thread(target=run3) t.start() while threading.active_count() != 1: print("\033[31m当前活跃的线程个数:%s\033[0m" %threading.active_count()) else: print("All the thread has task done!!!!") print(num1,num2)
上面程序使用了信号量,即统一时间只允许5个线程执行,虽然启动了10个线程;Bounded:绑定的;Semaphore:信号量,BondedSemaphore:绑定的信号量,即同一时间允许运行的线程数,上面程序的运行代码如下:
当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 3 6 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 当前活跃的线程个数:11 4 8 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 当前活跃的线程个数:9 6 12 5 10 7 14 2 4 当前活跃的线程个数:5 8 16 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 当前活跃的线程个数:4 11 22 当前活跃的线程个数:3 当前活跃的线程个数:3 当前活跃的线程个数:3 10 20 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 当前活跃的线程个数:2 9 18 All the thread has task done!!!! 11 22
从结果可以看出,执行是分批次执行的,同一时间只会有5个线程同时执行,当有线程执行完毕,会补充新的线程进来。
Events(事件)
An event is a simple synchronization object:事件是一个简单的同步对象;
the event represents an internal flag, and threads can wait for the flag to be set, or set or clear the flag themselves。(
该事件代表一个内部标志,线程可以等待标志设置,或设置或清除标志本身。)
event = threading.Event() #生命一个时间
event.wait() #一个客户端线程可以等待标志被设置(a client thread can wait for the flag to be set),检测标志位
event.set() #服务器线程可以设置或重置它(a server thread can set or reset it)
event.clear() #清楚标志位
If the flag is set, the wait method doesn’t do anything.(如果设置了标志,则等待方法不执行任何操作。)
If the flag is cleared, wait will block until it becomes set again.(如果标志位已清楚,等待将阻塞,直到它再次设置)。
Any number of threads may wait for the same event.(任何数量的线程可以等待同一事件)
下面来看一个红绿灯的程序,可以转换红绿灯以便车辆通行,当红灯的时候,车的线程等待,当绿灯的时候,车辆通行,就是两个线程交互的情况,使用的是事件(event),如下:
import threading,time def traffic_lights(): counter = 0 while True: if counter < 30: print("\033[42m即将转为绿灯,准备通行!!!\033[0m") event.set() #一分钟为一个轮回,30秒以内为绿灯 print("\033[32m绿灯,通行......\033[0m") elif counter >= 30 and counter <= 60: print("\033[41m即将转为红灯,请等待!!!\033[0m") event.clear() #清楚标志,转为红灯 print("\033[31m红灯中,禁止通行......\033[0m") elif counter > 60: counter = 0 #超过60秒重新计数,重新下一次循环 counter += 1 time.sleep(1) #一秒一秒的运行 def car(name): '''定义车的线程,汽车就检测是否有红绿灯,通行和等待''' while True: if event.is_set(): #存在标识位,说明是绿灯 '''检测,如果存在标志位,说明是绿灯中,车可以通行''' print("[%s] is running!!!" %name) else: '''标识位不存在,说明是红灯过程中''' print("[%s] is waitting!!!" %name) time.sleep(1) if __name__ == "__main__": try: event = threading.Event() lighter = threading.Thread(target=traffic_lights) lighter.start() '''启动多个车的线程''' for i in range(1): my_car = threading.Thread(target=car,args=("tesla",)) my_car.start() except KeyboardInterrupt as e: print("线程断开了!!!") except Exception as e: print("线程断开了!!!")
上面程序执行如下:
即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! [tesla] is running!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... 即将转为绿灯,准备通行!!! [tesla] is running!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... 即将转为绿灯,准备通行!!! [tesla] is running!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! [tesla] is running!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! [tesla] is running!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为绿灯,准备通行!!! 绿灯,通行...... [tesla] is running!!! 即将转为红灯,请等待!!! [tesla] is running!!! 红灯中,禁止通行...... [tesla] is waitting!!! 即将转为红灯,请等待!!! 红灯中,禁止通行...... 即将转为红灯,请等待!!! [tesla] is waitting!!! 红灯中,禁止通行...... [tesla] is waitting!!! 即将转为红灯,请等待!!! 红灯中,禁止通行...... [tesla] is waitting!!! 即将转为红灯,请等待!!! 红灯中,禁止通行...... [tesla] is waitting!!! 即将转为红灯,请等待!!! 红灯中,禁止通行...... 即将转为红灯,请等待!!! 红灯中,禁止通行...... [tesla] is waitting!!!
上面,我们定义了两个线程,并且实现了交互,使用的是事件,event.set():设置事件标识符,代表执行;event.clear():清除标识符,代表等待,只有当新的标识符被设置,才会通行。
import threading,time def traffic_lights(): '''设置红绿灯,会显示事件,以及由绿——黄——红、红———黄——绿的转换''' global counter #计时器 counter = 0 while True: if counter < 40: #绿灯通行中 event.set() '''绿灯中,可以通行''' print("\033[42mThe light is on green light,runing!!!\033[0m") print("剩余通行时间:%s" %(40-counter)) elif counter >40 and counter <= 43: event.clear() '''黄灯中,是由绿灯转为红灯的''' print("Yellow light is on,waitting!!!即将转为红灯!") elif counter > 43 and counter <= 63: '''红灯,由黄灯转换为红灯''' print("\033[41mThe red light is on!!! Waitting\033[0m") print("剩余红灯时间:%s" %(63-counter)) elif counter > 63 and counter <= 66: '''由红灯转换为红灯,即将转为绿灯''' print("The yewwlow is on,Waitting!!!即将转为红灯!!") elif counter > 66: counter = 0 counter += 1 time.sleep(1) def go_through(name): '''通行线程,根据上面红绿灯判断是否通行''' while True: if event.is_set(): """绿灯,可以通行""" print("[%s] is running!!!" %name) else: print("%s is waitting!!!" %name) time.sleep(1) if __name__ == "__main__": event = threading.Event() lights = threading.Thread(target=traffic_lights) lights.start() car = threading.Thread(target=go_through,args=("tesla",)) car.start()
上面程序中,我们实现了时间提醒,跟现实世界的红绿灯很相似,并且由绿--黄--红至红--黄--绿,实现来回的转换,如下所示:
The light is on green light,runing!!! 剩余通行时间:40 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:39 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:38 [tesla] is running!!! [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:37 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:36 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:35 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:34 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:33 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:32 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:31 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:30 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:29 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:28 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:27 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:26 The light is on green light,runing!!! 剩余通行时间:25 [tesla] is running!!! [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:24 The light is on green light,runing!!! [tesla] is running!!! 剩余通行时间:23 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:22 The light is on green light,runing!!! 剩余通行时间:21 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:20 [tesla] is running!!! [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:19 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:18 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:17 The light is on green light,runing!!! 剩余通行时间:16 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:15 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:14 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:13 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:12 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:11 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:10 [tesla] is running!!! [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:9 The light is on green light,runing!!! 剩余通行时间:8 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:7 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:6 [tesla] is running!!! [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:5 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:4 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:3 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:2 The light is on green light,runing!!! 剩余通行时间:1 [tesla] is running!!! [tesla] is running!!! [tesla] is running!!! Yellow light is on,waitting!!!即将转为红灯! tesla is waitting!!! Yellow light is on,waitting!!!即将转为红灯! Yellow light is on,waitting!!!即将转为红灯! tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:19 tesla is waitting!!! The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:18 The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:17 The red light is on!!! Waitting 剩余红灯时间:16 tesla is waitting!!! The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:15 tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:14 The red light is on!!! Waitting 剩余红灯时间:13 tesla is waitting!!! tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:12 tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:11 tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:10 The red light is on!!! Waitting 剩余红灯时间:9 tesla is waitting!!! The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:8 tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:7 The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:6 The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:5 tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:4 The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:3 The red light is on!!! Waitting tesla is waitting!!! 剩余红灯时间:2 tesla is waitting!!! The red light is on!!! Waitting 剩余红灯时间:1 The red light is on!!! Waitting 剩余红灯时间:0 tesla is waitting!!! tesla is waitting!!! The yewwlow is on,Waitting!!!即将转为红灯!! tesla is waitting!!! The yewwlow is on,Waitting!!!即将转为红灯!! tesla is waitting!!! The yewwlow is on,Waitting!!!即将转为红灯!! tesla is waitting!!! tesla is waitting!!! The light is on green light,runing!!! 剩余通行时间:39 [tesla] is running!!! The light is on green light,runing!!! 剩余通行时间:38 [tesla] is running!!!
上面程序中,我们实现了红绿灯的交替,即时间的设置与取消,根据两个状态来判断,只有设置的时候,绿灯才通行,取消的时候,都是等待。