eventlet引发的学习-初识多线程

参考

python多线程

python threading模块官方文档

初识多线程

python多线程中有关于python多线程的详细基础知识,此处不在赘述,只是简单总结下:

  • python中自带了2个模块支持多线程:
    * thread:提供相对底层的多线程
    * threading:提供了2种创建多线程的方式:
    * threading.Thread(target,args)对象,target即为要执行的函数
    * 创建自己的类继承threading.Thread,并实现__init__以及run方法,然后创建对象

测试代码

threading模块创建Thread对象方式

from threading import Thread
import time

G_COUNT = 100000000

def func1():
    for i in range(10):
        print("Func1:%s at %s" % (i,time.time()))
        time.sleep(1)

def func2():
    for i in range(10):
        print("Func2:%s at %s" % (i, time.time()))
        time.sleep(1)


def main():

    t1 = Thread(target=func1)
    t2 = Thread(target=func2)

    t1.start()
    t2.start()

    t1.join()
    t2.join()

if __name__ == "__main__":
    main()

执行的结果如下:

Func1:0 at 1456760385.98
Func2:0 at 1456760385.98
Func1:1 at 1456760386.99
Func2:1 at 1456760386.99
Func1:2 at 1456760387.99
Func2:2 at 1456760387.99
Func2:3 at 1456760388.99
Func1:3 at 1456760388.99
Func1:4 at 1456760389.99
Func2:4 at 1456760389.99
Func1:5 at 1456760391.0
Func2:5 at 1456760391.0
Func1:6 at 1456760392.0
Func2:6 at 1456760392.0
Func1:7 at 1456760393.0
Func2:7 at 1456760393.0
Func1:8 at 1456760394.0
Func2:8 at 1456760394.0
Func1:9 at 1456760395.0
Func2:9 at 1456760395.0

threading模块继承Thread类方式

import threading
import time


class MyThread(threading.Thread):

    def __init__(self, thread_name, count):
        super(MyThread, self).__init__()
        self.thread_name = thread_name
        self.count = count

    def run(self):
        print "Starting " + self.name
        print_time(self.name, count)
        print "Ending " + self.name


def print_time(name, count):
    for i in range(count):
        print "%s:%s" % (name, time.ctime(time.time()))
        time.sleep(1)

count = 5
thread1 = MyThread("Thread-1", count)
thread2 = MyThread("Thread-2", count)

thread1.start()
thread2.start()

执行的结果如下:

Starting Thread-1
Starting Thread-2

Thread-1:Mon Feb 29 23:37:28 2016
Thread-2:Mon Feb 29 23:37:28 2016
Thread-1:Mon Feb 29 23:37:29 2016
Thread-2:Mon Feb 29 23:37:29 2016
Thread-1:Mon Feb 29 23:37:30 2016
Thread-2:Mon Feb 29 23:37:30 2016
Thread-1:Mon Feb 29 23:37:31 2016
Thread-2:Mon Feb 29 23:37:31 2016
Thread-1:Mon Feb 29 23:37:32 2016
Thread-2:Mon Feb 29 23:37:32 2016
Ending Thread-1
Ending Thread-2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值