Home > Backend Development > Python Tutorial > How to install threading in python

How to install threading in python

(*-*)浩
Release: 2019-07-05 11:58:08
Original
16636 people have browsed it

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.

How to install threading in python

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(&#39;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)
Copy after login

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.
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template