线程过早执行而不调用Start
在Python中,创建线程对象不会自动开始执行。但是,线程有可能甚至在调用 start() 方法之前就开始运行。此行为可归因于线程创建不当,解释如下。
考虑以下代码片段:
t1 = threading.Thread(target=self.read) print("something") t2 = threading.Thread(target=self.runChecks(), args=(self,))
在此示例中,self.read 函数旨在无限期运行,阻止程序到达后续的打印语句。但是,程序完全跳过打印语句。这种行为看起来很反常,因为在线程上调用 start() 通常会允许其执行开始并线性进行。
此问题的解释在于用于创建线程的语法。在第一行中, self.read 之后的括号有效地调用该函数并将其返回值指定为线程的目标。这意味着 self.read 实际上是在主线程中运行,而不是新创建的线程。
要解决此问题,只需从目标参数中删除括号即可:
t1 = threading.Thread(target=self.read) t1.start() print("something")
这可以确保self.read 成为线程要运行的目标函数,并且仅在调用 t1.start() 后才开始执行。
对于需要参数的目标,请使用threading.Thread 的 args 或 kwargs 参数或使用 lambda 表达式。例如:
thread = threading.Thread(target=lambda: f(a, b, x=c))
此语法将函数及其参数传递给线程,确保正确执行。
请记住,lambda 函数在使用时评估其参数,而不是在定义时评估其参数。这意味着在调度线程之前重新定义变量可能会导致意外结果。
以上是为什么我的线程在 Python 中调用 `start()` 之前运行?的详细内容。更多信息请关注PHP中文网其他相关文章!

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

WebStorm Mac版
好用的JavaScript开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境