Python的多线程支持-pybatis的准备阶段(十一)
来源:互联网 发布:php仓库管理mysql 编辑:程序博客网 时间:2024/06/06 12:23
在考虑pybatis中是不是要用多线程呢?刚刚在技术群里问了一下。用户的请求大概会是从web服务器中发出来的。
那么,web服务器本身就会对请求使用多线程来处理。那么orm就不用处理了。但是还是要学习一下多线程的知识。
在py中使用线程有两种方式:
1、自己用函数包装线程对象
2、继承线程类。
先看第一种情况:
import timeimport threaddef timer(no, interval): cnt = 0 while cnt<10: print 'Thread:(%d) Time:%s/n'%(no, time.ctime()) time.sleep(interval) cnt+=1 thread.exit_thread() def test(): #Use thread.start_new_thread() to create 2 new threads thread.start_new_thread(timer, (1,1)) thread.start_new_thread(timer, (2,2)) if __name__=='__main__': test()
上面这种方法中,使用thread的start_new_thread函数来创建一个线程并执行参数中设定的方法。第一个参数是线程的函数。第二个参数是线程函数的参数
看第二种情况:
import threadingimport timeclass timer(threading.Thread): #The timer class is derived from the class threading.Thread def __init__(self, num, interval): threading.Thread.__init__(self) self.thread_num = num self.interval = interval self.thread_stop = False def run(self): #Overwrite run() method, put what you want the thread do here while not self.thread_stop: print 'Thread Object(%d), Time:%s/n' %(self.thread_num, time.ctime()) time.sleep(self.interval) def stop(self): self.thread_stop = True def test(): thread1 = timer(1, 1) thread2 = timer(2, 2) thread1.start() thread2.start() time.sleep(10) thread1.stop() thread2.stop() return if __name__ == '__main__': test()
上面的这个例子继承了threading.Thread类。覆盖run方法就可以了。
------------------------------------------------------------------------
这是线程的基本用法。
- Python的多线程支持-pybatis的准备阶段(十一)
- Python中Mysqldb的使用以及事务的支持-pybatis首次露面-pybatis的准备阶段(十)
- 给PyBatis添加数据库连接池支持-pybatis的准备阶段(十二)
- Python解析xml文件-pybatis的准备阶段(二)
- Python中的静态方法-pybatis的准备阶段(五)
- Python操作MySql-pybatis的准备阶段(三)
- Python中的异常-pybatis的准备阶段(四)
- Python解析xml-pybatis的准备阶段(八)
- Python中globals和locals的区别-pybatis的准备阶段(六)
- Python中的反射(自省)-pybatis的准备阶段(一)
- Python中动态导入模块-pybatis的准备阶段(七)
- Python接口与类继承学习-pybatis的准备阶段(九)
- 准备阶段:00 学习python的目标!
- python支持多线程的爬虫
- python多线程编程(1): python对多线程的支持
- Python多线程编程1----Python对多线程的支持
- python多线程编程(1): python对多线程的支持
- python多线程编程(1): python对多线程的支持
- js加强(二)
- 求助。安装WDK。error LNK1181
- 存储过程
- 自己创建CoreData所需要的相应类
- 如何提高转化率
- Python的多线程支持-pybatis的准备阶段(十一)
- C++ 数组array与vector的比较
- 网赚项目之站群第三课 站群上线以及注意事项
- hibernate主要接口和类(笔记)
- IntelliJ IDEA改变背景色
- 初步理解java中的反射和内省及反射和内省的用法大集合
- 表格(TableViewer类)
- 网赚项目之站群第四课站群的文章采集与伪原创
- Hadoop 如何区分 繁多的版本号