Python 3 uses threads

Keywords: Python

The Python 2 standard library provides two modules threading and threading to support multi-threading.
Thead has some drawbacks that are discarded in Python 3. For compatibility, Python 3 renames threads to "_thread", which is recommended for direct use in Python 3.

Creating Thread Objects

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

Description of parameters:

group should be None; it should be retained to extend the ThreadGroup class implementation in the future.
target is a callable object for the run() method call. The default is None, meaning that no method needs to be invoked.
Name is the thread name. By default, a unique name is formed by the "Thread-N" format, where N is a small decimal number.
args is a parameter tuple used to call the objective function. The default is ().
kwargs is a keyword parameter dictionary used to call the objective function. The default is {}.
If daemon is not None, the thread will be explicitly set to daemon mode, regardless of whether the thread is daemon mode or not. If it is None (default), the thread will inherit the daemon attributes of the current thread.

Several Methods of Thread Objects

start() starts thread activity.
run() represents the method of thread activity.
join(timeout=None) waits until the end of the thread

There are two ways to use threads: functions or classes to wrap threaded objects

Example 1: Using functions

import random
import threading 
import time

def run(threadName):
    for i in range(5):
        time.sleep(random.random())
        print('{} : {}'.format(threadName, i))

t1 = threading.Thread(target=run, args=('thread 1',))
t1.start()
t2 = threading.Thread(target=run, args=('thread 2',))
t2.start()

Example 2: Using classes

import random
import threading 
import time

class test(threading.Thread):
    def __init__(self,name):
        super().__init__()
        self.name = name
    def run(self):
        for i in range(5):
            time.sleep(random.random())
            print('{} : {}'.format(self.name, i))
        
t1 = test('thread 1')
t1.start()
t2 = test('thread 2')
t2.start()

Examples 1 and 2 show the results of a run:

thread 1 : 0
thread 1 : 1
thread 2 : 0
thread 1 : 2
thread 2 : 1
thread 2 : 2
thread 1 : 3
thread 2 : 3
thread 2 : 4
thread 1 : 4

Example 3:

import random
import threading 
import time

def run(threadName,):
    print('{} start'.format(threadName))
    time.sleep(random.random())
    print('{} end'.format(threadName))

threads = []

#Create 10 Thread Objects
for i in range(10):
    threads.append(threading.Thread(target=run,args=('thread ' + str(i),)))

#Running threads
for th in threads:
    th.start()

#Wait until the end of the thread.
for th in threads:
    th.join()

print("finished")

One operation result:

thread 0 start
thread 1 start
thread 2 start
thread 3 start
thread 4 start
thread 5 start
thread 6 start
thread 7 start
thread 8 start
thread 9 start
thread 2 end
thread 3 end
thread 9 end
thread 0 end
thread 1 end
thread 8 end
thread 6 end
thread 4 end
thread 7 end
thread 5 end
finished

Posted by jshowe on Wed, 28 Aug 2019 04:30:07 -0700