Basic use of threading library in python

Introduction

The threading module contains rich functions about thread operations, including: common thread functions, thread objects, lock objects, recursive lock objects, event objects, condition variable objects, semaphore objects, timer objects, and fence objects.
Due to the existence of GIL (global interpreter lock) in python, true parallel threads cannot be realized, but concurrent threads can only be realized.
This article introduces the basic methods of the threading library, and the other complex methods will be updated when they are used.

Create thread

The first method: call threading.Thread

import threading
# target 相当于C中的 void*(*p)(),args是参数列表
thread = threading.Thread(target=target, args=[i])

The second method: create a class that inherits threading.Thread

import time
import threading


class OwnThread(threading.Thread):
    def __init__(self, para, sleep):
        # 先调用父类的threading.Thread.__init__方法
        super().__init__()
        self.para = para
        self.sleep = sleep

	# 覆盖了父类的run方法
    def run(self):
        """线程内容"""
        time.sleep(self.sleep)
        print(self.para)


def main():
    # 创建线程
    thread_hello = TestThread('hello', 1)
    # 启动线程
    thread_hello.start()
    print('Main thread has ended!')


if __name__ == '__main__':
    main()

Start thread

After starting the thread, thread starts to execute the function specified by target/function covered by run

thread = threading.Thread(target=target, args=[i])
thread.start()

join method

Like the traditional join concept, the main thread will block and wait for the join thread to finish executing, regardless of whether the thread executing the join is a demoon or not.

thread = threading.Thread(target=target, args=[i])
thread.join()

lock

Use locks to protect global resources (can't help but remind me of the system software that I postponed

import threading
import time

lock=threading.Lock()
fuck = 0


def target(second):
    global fuck
    lock.acquire()
    print(fuck)
    tmp = fuck+1
    time.sleep(0.001)
    fuck = tmp
    lock.release()


for i in range(1,1000):
    thread = threading.Thread(target=target, args=[i])
    thread.start()

Guess you like

Origin blog.csdn.net/weixin_44602409/article/details/107299196