python(29)-线程与进程

线程调用两种方式:函数和类
 

import threading
import time


def funs(num):                                    # 定义每个线程要运行的函数
    print("funs Thread on number:%s" % num)
    time.sleep(3)
    
class MyThread(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num

    def run(self):                                # 定义每个线程要运行的函数
        print("MyThread  on number:%s" % self.num)
        time.sleep(3)

if __name__ == '__main__':
    t1 = threading.Thread(target=funs, args=(1,))  # threading.Thread  输入参数(函数名,数字)
    t2 = threading.Thread(target=funs, args=(2,))  # 生成另一个线程实例

    t1.start()                                     # 启动线程
    t2.start()                                     # 启动另一个线程

    print(t1.getName())                            # 获取线程名
    print(t2.getName())

    tc1 = MyThread(1)                              #定义一个实例,把数字放进去
    tc2 = MyThread(2)
    tc1.start()
    tc2.start()
    print(tc1.getName())                            # 获取线程名
    print(tc2.getName())

进程:一般都是父进程调用子进程的。下文为调用与进程信息显示。

from multiprocessing import Process
import os,time,threading

#进程信息 父进程ID 自己的进程ID
#每一个进程都是由父进程启动的
def info(title):
    print(title)
    print('module name:', __name__)        #模块名称
    print('parent process:', os.getppid()) #父进程的ID
    print('process id:', os.getpid())      #自己的进程ID
    print("\n\n")


def fun(name):                  #调用了info
    info('\033[31; called function f\033[0m')
    print('hello', name)


if __name__ == '__main__':
    info('\033[32; main process line\033[0m')
    p = Process(target=fun, args=('bob',))
    p.start()
    p.join()

 

posted @ 2020-04-04 21:34  jasmineTang  阅读(44)  评论(0)    收藏  举报