在Python中通过threading模块定义和调用线程的方法

本文介绍了在Python中通过threading模块定义和调用线程的方法,包括使用target指定执行函数、确定当前线程、配合logging模块以及通过继承Thread类创建线程。示例代码展示了如何实现和运行线程。
摘要由CSDN通过智能技术生成

由于著名的GIL的存在,Python中虽然能创建多条线程,但却不能同时执行…anyway,这里我们还是来学习一下在Python中通过threading模块定义和调用线程的方法
定义线程

最简单的方法:使用target指定线程要执行的目标函数,再使用start()启动。

语法:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

group恒为None,保留未来使用。target为要执行的函数名。name为线程名,默认为Thread-N,通常使用默认即可。但服务器端程序线程功能不同时,建议命名。

#!/usr/bin/env python3
# coding=utf-8
import threading
 
def function(i):
  print ("function called by thread {0}".format(i))
threads = []
 
for i in range(5):
  t = threading.Thread(target=function , args=(i,))
  threads.append(t)
  t.start()
  t.join()

执行结果

$ ./threading_define.py 
function called by thread 0
function called by thread 1
function called by thread 2
function called by thread 3
function called by thread 4

确定当前线程


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值