Python 3 线程

函数式

调用 threading 模块中的start_new_thread()函数来产生新线程。

import threading
import time


def execute_fun(thread_name, age):
    time.sleep(2)
    print(thread_name)
    print(age)
    print(threading.current_thread())
    print('count ', threading.active_count())


print(str(threading.current_thread()) + '   ' + str(threading.active_count()))

threading._start_new_thread(execute_fun, (), {'thread_name': 'thread_1', 'age': 1})
thread2 = threading._start_new_thread(execute_fun, ('thread_2', 2,))
print(type(thread2))

while True:
    pass

函数参数说明

def start_new_thread(function, args, kwargs=None): # real signature unknown; restored from __doc__
    """
    start_new_thread(function, args[, kwargs])
    (start_new() is an obsolete synonym)
    
    Start a new thread and return its identifier.  The thread will call the
    function with positional arguments from the tuple args and keyword arguments
    taken from the optional dictionary kwargs.  The thread exits when the
    function returns; the return value is ignored.  The thread will also exit
    when the function raises an unhandled exception; a stack trace will be
    printed unless the exception is SystemExit.
    """
    pass
  • function: 线程调用的函数名
  • args: 元组类型,函数所需要的参数,必须参数
  • kwargs:关键字参数,字典类型,传递此参数的时候,args 为空元组

返回一个线程的标识符

start_new_thread 并不是马上启动了线程,所以需要在主线程结束前启动了,所以加上个死循环或者time.sleep(10)来确保真正启动了

继承Thread

通过继承 thread.Thread 重写run 方法

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, thread_name, other_arg):
        threading.Thread.__init__(self)#记得调用父类的初始化函数(构造函数)
        self.name = thread_name
        self.other_arg = other_arg

    def run(self):
        time.sleep(5)

        print(self.other_arg)


thread1 = MyThread('thread_1', 12)

thread1.start()
# thread1.join()

thread1 线程 启动后,主线程会等待它结束之后才会结束自己

线程同步

使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。

import threading
import time

my_list = [0, 0, 0, 0, 0, 0, 0]


class ChangeThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        thread_lock.acquire()
        for i in range(0, len(my_list)):
            my_list[i] = 1
            time.sleep(0.1)
        thread_lock.release()


class PrintThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        thread_lock.acquire()

        for item in my_list:
            print(item)
            time.sleep(0.1)
        thread_lock.release()


thread_lock = threading.Lock()

print_thread = PrintThread()
change_thread = ChangeThread()

change_thread.start()
print_thread.start()

change_thread.join()
print_thread.join()

Lock 和 RLock区别

线程优先级队列( Queue)

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。

Python 3 线程_第1张图片
image

相关

http://www.runoob.com/python3/python3-multithreading.html

你可能感兴趣的:(Python 3 线程)