Python与多线程

≡放荡痞女 提交于 2020-01-10 12:42:36

感谢这位博主帮我打开了多线程的门https://blog.csdn.net/m0_38011218/article/details/81938261

首先我之前学的java多线程,在java.lang包中有thread类。我们只要集成这个类然后start()。很简单有四种方式

详细见https://www.cnblogs.com/shoshana-kong/p/9071602.html

 

python具有异曲同工之妙

函数方式;就是简单调用库中的方法 

import threading
import time


def sing(num):
    for i in range(num):
        print("sing%d" % i)
        time.sleep(1)


def dance(num):
    for i in range(num):
        print("dancd%d" % i)
        time.sleep(1.5)


if __name__ == '__main__':
    t_sing = threading.Thread(target=sing, args=(5, ))
    t_dance = threading.Thread(target=dance, args=(5, ))
    t_sing.start()
    t_dance.start()

time.sleep()是为了让运行的顺序明显一点

 第二种继承方式:

import threading
import time

class Mythread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = 'i\'m' + self.name + '@' +str(i)
            print(msg)

def test():
    for i in range(5):
        t=Mythread()
        t.start()

if __name__ == '__main__':
    test()

join方法可以阻塞主进程(注意只能阻塞主进程,其他子进程是不能阻塞的),直到 子线程执行完,再解阻塞。

无join前

import threading
import time

class Mythread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = 'i\'m' + self.name + '@' +str(i)
            print(msg)

def test():
    for i in range(2):
        t=Mythread()
        t.start()

if __name__ == '__main__':
    test()
    print("hello")

join之后:

import threading
import time

class Mythread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = 'i\'m' + self.name + '@' +str(i)
            print(msg)

def test():
    for i in range(2):
        t=Mythread()
        t.start()
        t.join()

if __name__ == '__main__':
    test()
    print("hello")

先阻塞 了主进程,所以hello是最后输出的

 

最后让我想起了仿佛在昨日(其实一年前)考完的操作系统,时间片轮转问题,互斥锁问题,wow果然操作系统是门玄学,现在忘得差不多了

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!