How to create threads in python

Posted by scooterlibby on Wed, 04 Dec 2019 03:55:26 +0100

Before talking about how to create threads, I think it's necessary to explain what GIL is. The full name of GIL is global interpreter lock, that is, global interpreter lock.

Because of the existence of GIL, only one thread can execute on one CPU at a time, that is to say, we can't take advantage of multi-core, because even multi-core,

At the same time, only one thread can execute on one CPU. This is also the reason why python was slowly tucking away.

Of course, since it is a lock, there will be a time of release naturally, and GIL is no exception. GIL releases the GIL lock based on the number of lines or time slices of bytecode executed,

When encountering IO operation, GIL lock will also be released, so this is not to say that as soon as the thread gets the lock, it will not be released until the execution is completed. We can use the following example to illustrate.

import threading

total = 0

def add():
    global total
    for i in range(1000000):
        total += 1

def desc():
    global total
    for i in range(1000000):
        total -= 1

if __name__ == '__main__':
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=desc)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()
    print(total)

The output result of the above code is not 0, which is not what we want, but it also shows that the thread is switched off when it is half executed.

If we want to keep the data synchronized, we have to lock it.

We can guarantee the data synchronization by importing the lock. The code is as follows.

import threading
from threading import Lock

total = 0
lock = Lock()

def add():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total += 1
        lock.release()

def desc():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total -= 1
        lock.release()

if __name__ == '__main__':
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=desc)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()
    print(total)

Run after the lock is applied. The result is 0

In python, the module needed to create a thread is threading, as shown in the figure below. This is the first way to create a thread. The args parameter can not be used, but if you want to write a parameter, it must be an iterative object.

import threading

def add(a):
    a += 1


if __name__ == '__main__':
    thread1 = threading.Thread(target=add,args=(0,))
    thread1.start()

The second way to create a thread is to create a process by inheriting the thread class.

import threading

class Add(threading.Thread):
    def __init__(self,a):
        super().__init__()
        self.a = a

    def run(self):
        for i in range(1000000):
            self.a += 1

if __name__ == '__main__':
    ad = Add(0)
    ad.start()

When you create a process in this way, you need to overload the run method.

Topics: Python