Python basic points: a multi-threaded, threading module, create a sub-thread example of in two ways

This article describes the Python multi-threading, threading module, two ways to create a child thread, analyzes the principle and create a sub-thread-related skills to achieve Python thread form with an example, a friend in need can refer

Python basic points: a multi-threaded, threading module, create a sub-thread example of in two ways

GIL (Global Interpreter Lock) is a C language version of the Python interpreter and some secondary school, there is GIL makes multithreaded efficiency is low (which thread to grab the lock, which thread is executed). In the IO-intensive process, multi-thread is still higher than the single-threaded efficiency (GIL automatic switching multithreading blocked by IO).

Three ways to solve the problem GIL (Global Interpreter Lock) are:

1, do not use the C language version of the Python interpreter.

2, let the child thread running code in other languages ​​(for example: the main thread running Python code, sub-thread running C language code (dynamic library C language)).

3, instead of multi-process multi-threaded (multi-process can take advantage of multi-core CPU).

The first way to create a sub-thread:

demo.py (sub-tasks specified by the thread function name):

在学习过程中有什么不懂得可以加我的
python学习交流扣扣qun,×××
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容
1 import threading
2 def test1():
3 print("子线程运行了...")
4 def main():
5 # 通过 target=函数名 的方式定义子线程
6 t1 = threading.Thread(target=test1) # 通过target指定子线程要执行的任务。可以通过args=元组 来指定test1的参数。
7 t1.start() # 只有在调用start方法后才会创建子线程并执行
8 # threading.enumerate() 打印正在执行的线程,包括主线程和子线程
9 print(threading.enumerate()) # [<_MainThread(MainThread, started 139724821161728)>, <Thread(Thread-1, started 139724795434752)>]
10 # 当子线程没有结束时,主线程也不会结束。 当主线程结束后,所有的子线程也会结束。
11 if __name__ == "__main__":
12 main()

operation result:

Child thread running ...

[<_MainThread(MainThread, started 7076)>, <Thread(Thread-1, started 2832)>]​

The second way to create a child thread:

demo.py (child thread defined by categories):

1 #coding=utf-8
2 import threading
3 # 通过类定义子线程。 继承threading.Thread类
4 class MyThread(threading.Thread):
5 # 开启子线程时,会自动执行run函数
6 def run(self):
7 print(self.name) # Thread-1 name属性中保存的是当前线程的名字
8 def main():
9 t = MyThread() # 实例化自定义的子线程
10 t.start() # 开启子线程
11 if __name__ == '__main__':
12 main()

operation result:

Thread-1

The article also think I may wish to take your collection together, have any comments or opinions are welcome to comment!

Guess you like

Origin blog.51cto.com/14568144/2444888