python多线程操作实例
一、python多线程
因为CPython的实现使用了Global Interpereter Lock(GIL),使得python中同一时刻只有一个线程在执行,从而简化了python解释器的实现,且python对象模型天然地线程安全。如果你想你的应用程序在多核的机器上使用更好的资源,建议使用multiprocessing或concurrent.futures.processpoolexecutor。但是如果你的程序是IO密集型,则使用线程仍然是很好的选择。
二、python多线程使用的两种方法
实例:
import threading
import time
def worker(num):
print (threading.currentThread().getName() + ' start')
time.sleep(10)
print (threading.currentThread().getName() + ' running')
print (threading.currentThread().getName() + " " + str(num))
print (threading.currentThread().getName() + ' exit')
def deamon():
print (threading.currentThread().getName() + ' start')
time.sleep(20)
print (threading.currentThread().getName() + ' running')
print (threading.currentThread().getName() + ' exit')
print(threading.currentThread().getName())
d = threading.Thread(name='deamon', target=deamon)
d.setDaemon(True)
d.start()
w = threading.Thread(name='worker', target=worker, args=(10,))
w.start()
class myWorker(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
self.thread_stop = False
def run(self):
print (self.getName()+' start')
time.sleep(30)
print (self.getName()+' running')
print (self.getName()+" " + str(self.num))
print (self.getName()+' exit')
mw = myWorker(30)
mw.setName("MyWorker")
mw.start()
print(threading.currentThread().getName())
print("All threads:")
print("------------")
for th in threading.enumerate():
print(th.getName())
print("------------")
d.join()
w.join()
mw.join()
print(threading.currentThread().getName())
运行结果如下:
1)python线程使用的两种方法:
**直接调用threading.Thread来构造thread对象,Thread的参数如下:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
group为None;
target为线程将要执行的功能函数;
name为线程的名字,也可以在对象构造后调用setName()来设定;
args为tuple类型的参数,可以为多个,如果只有一个也的使用tuple的形式传入,例如(1,);
kwargs为dict类型的参数,也即位命名参数;
**实现自己的threading.Thread的子类,需要重载__init__()和run()。
2)threading.Thread对象的其他方法:
start(),用来启动线程;
join(), 等待直到线程结束;
setDeamon(), 设置线程为deamon线程,必须在start()调用前调用,默认为非demon。
注意: python的主线程在没有非deamon线程存在时就会退出。
3)threading的静态方法:
threading.current_thread() , 用来获得当前的线程;
threading.enumerate() , 用来多的当前存活的所有线程;
threading.Timer 定时器,其实是thread的一个字类型,使用如下:
def hello(): print("hello, world")
t = Timer(30.0, hello)
t.start()
4)logging是线程安全的
logging 模块是线程安全的,所以可以使用logging来帮助调试多线程程序。
import logging
logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)
logging.debug("wait_for_event_timeout starting")

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
