Since threads are execution units directly supported by the operating system, high-level languages usually have built-in multi-threading support, and Python is no exception. Moreover, Python threads are real Posix Threads, not simulated threads.
Python's standard library provides two modules: _thread and threading. _thread is a low-level module, and threading is a high-level module, which encapsulates _thread. In most cases, we only need to use the advanced module threading. (Recommended learning: Python video tutorial)
To start a thread is to pass a function in and create a Thread instance, and then call start() to start execution:
import time, threading# 新线程执行的代码:def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n = n + 1 print('thread %s >>> %s' % (threading.current_thread().name, n)) time.sleep(1) print('thread %s ended.' % threading.current_thread().name) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended.' % threading.current_thread().name)
Execution The results are as follows:
thread MainThread is running... thread LoopThread is running... thread LoopThread >>> 1 thread LoopThread >>> 2 thread LoopThread >>> 3 thread LoopThread >>> 4 thread LoopThread >>> 5 thread LoopThread ended. thread MainThread ended.
Since any process will start a thread by default, we call this thread the main thread, and the main thread can start new threads. Python's threading module has a current_thread() function, which Always returns an instance of the current thread. The name of the main thread instance is MainThread, and the name of the sub-thread is specified when it is created. We use LoopThread to name the sub-thread. The name is only used for display when printing and has no other meaning at all. If you can't name it, Python will automatically name the thread Thread-1, Thread-2...
For more Python related technical articles, please visitPython tutorial column to learn!
The above is the detailed content of How to install threading in python. For more information, please follow other related articles on the PHP Chinese website!