Reference: www.liaoxuefeng.com/wiki/101695…

Multitasking can be done by multiple processes or by multiple threads within a process.

A process is composed of several threads, each process has at least one thread.

threading

import time
import threading


# Code executed by the new thread
def loop(n: int) :
    print(F 'thread{threading.current_thread().name}Running... ')
    while n < 5:
        n = n + 1
        print(F 'thread{threading.current_thread().name}>>>{n}')
        time.sleep(1)
    print(F 'thread{threading.current_thread().name}The end. ')


# current_thread() returns an instance of the current thread
print(F the main thread{threading.current_thread().name}Running ')

# target= method to execute, name= thread name (thread name is only used for print display), args=(parameter to execute function,)
t = threading.Thread(target=loop, name='LoopThread', args=(0, ))
t.start()
t.join()

Any process will start a thread by default. In this case, MainThread is started
print(F the main thread{threading.current_thread().name}The end of the ')
Copy the code

Running results:

/ Users/zy7y/PycharmProjects/demo/venv/bin/python/Users/zy7y/PycharmProjects/demo/threading_demo MainThread py the main thread is running LoopThread running... Thread LoopThread>>>1 thread LoopThread>>>2 thread LoopThread>>>3 thread LoopThread>> 4 thread LoopThread>>>5 thread LoopThread Ends. MainThread End Process finished with exit code 0Copy the code

Lock

In multiple processes, the same variable does not affect each other in each process.

In multithreading, all variables are shared by all threads, that is, any variable can be modified by any thread. The biggest risk of sharing data between threads is that multiple threads change a variable at the same time

import time
import threading

# Bank account
balance = 0

Example # lock
lock = threading.Lock()


def change_it(n: int) :
    The result should be 0
    # global (shared) variable:
    global balance
    balance = balance + n
    balance = balance - n


def run_thread(n: int) :
    for i in range(1000000) :# acquiring a lock
        lock.acquire()
        try:
            change_it(n)
        finally:
            # releases the lock
            lock.release()


t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8, ))

t1.start()
t2.start()

t1.join()
t2.join()

print(balance)
Copy the code