线程和进程

简单创建线程: 

通过threading.Thread来创建线程。

thd = threading.Thread(target=hello)

上行代码创造出了一个线程。该线程可实现输出hello world语句三遍的功能。

thd.start() #开始线程

import threading
import time

def hello():
    for i in range(3):
        print('hello world……%d'%i)
        time.sleep(1)

if __name__ == '__main__':
    thd = threading.Thread(target=hello)
    thd.start()
hello world……0
hello world……1
hello world……2

另一个创建线程的方法是使用run方法。

import threading
import time

def hello():
    for i in range(3):
        print('hello world……%d'%i)
        time.sleep(1)
class THD(threading.Thread):

    def run(self):
        for i in range(3):
            print('hello world……%d' % i)
            time.sleep(1)

if __name__ == '__main__':
    thd = THD()
    thd.start()

以上创建的都为子线程,因为主线程就是程序本身,程序运行完毕,主线程结束。

创建进程:

和创建线程类似,用multiprocessing.Process来创建。

import time
import multiprocessing

def hello():
    for i in range(3):
        print('hello world……%d'%i)
        time.sleep(1)

if __name__ == '__main__':
    por = multiprocessing.Process(target=hello)
    por.start()
hello world……0
hello world……1
hello world……2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值