Python combat: Use python multi-threading

Stones from other hills, can learn ------ "The Book of Songs Xiaoya Heming"

I. Introduction

If everyone on the thread of what is, what is the process still have doubts, please Google search, this is no longer redundant description of these concepts, this paper aims to summarize python multi-threading in several ways.

Python3 common thread in two modules:

  • _thread
  • threading (recommended)

thread module has been abandoned. The user can use instead of threading module. So, you can no longer use the "thread" module in Python3 in. For compatibility, Python3 the thread rename "_thread".

Here are three ways to implement multiple threads using actual cases.

Two, Python multi-threaded

1. _thread multi-threaded

Python threads used in two ways: with a function or to wrap the Thread object class.
Functional: Call _thread module start_new_thread () function to generate a new thread. The syntax is as follows:

_thread.start_new_thread ( function, args[, kwargs] )

Parameter Description:

  • function - thread function.
  • args - arguments passed to the thread function, he must be a tuple type.
  • kwargs - Optional.

Note: _thread process for when to exit without any control. When the main thread, all other threads have also forcibly ended. It will not issue a warning or proper cleanup. Thus python multithreading generally use more advanced threading module, which provides complete thread control mechanisms and semaphore mechanism.

Case:

# -*- coding: utf-8 -*-
import _thread
import time


def print_time(thread_name, sleep_time):
    for i in range(5):
        time.sleep(sleep_time)
        print("threadName: %s, time is %s" % (thread_name, time.ctime(time.time())))


if __name__ == "__main__":
    try:
        _thread.start_new_thread(print_time, ("thread-1", 2))
        _thread.start_new_thread(print_time, ("thread-2", 2))
    except:
        print("线程为启动")

while 1:
    pass

2. Create a multi-threaded through threading.Thread

python3.x create a new thread by threading module has two ways: one is by threading.Thread (Target = executable Method) - i.e. passed to an executable method of the Thread object (or objects);

# -*- coding: utf-8 -*-
import time
import threading


def print_time():
    for i in range(5):
        time.sleep(1)
        print("threadName: %s, time is %s" % (threading.current_thread().getName(),
                                              time.ctime(time.time())))


if __name__ == "__main__":
    t = threading.Thread(target=print_time)
    t2 = threading.Thread(target=print_time)
    t.start()
    t2.start()
    t.join() # join是阻塞当前线程(此处的当前线程时主线程) 主线程直到Thread-1结束之后才结束
    print("主线程打印内容")

3. Create multi-threaded through inheritance threading.Thread defined subclass

We can be created directly inherited from threading.Thread a new sub-class, and after the call start instantiate () method to start a new thread, which it calls the thread's run () method:

# -*- coding: utf-8 -*-

import threading
import time

exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print("退出线程:" + self.name)


def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1


if __name__ == "__main__":
    # 创建新线程
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)

    # 开启新线程
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print("退出主线程")
Published 19 original articles · won praise 67 · views 20000 +

Guess you like

Origin blog.csdn.net/m1090760001/article/details/103467195