简体   繁体   English

Python:为长时间运行的后台进程生成或线程?

[英]Python: spawn or thread for long running background process?

I am planning to make a long running background process with Python but I am still unsure whether to use os.spawnle or thread. 我打算用Python进行长时间运行的后台进程,但我仍然不确定是使用os.spawnle还是使用线程。 I've only read about it therefore I have not much experience with either spawn or thread. 我只读过它,因此我对spawn或thread没有多少经验。 Is there any rule of thumb when to use which? 有什么经验法则何时使用?

Thanks heaps 谢谢堆

Be sure that you take the Global Interpreter Lock into account. 请务必考虑Global Interpreter Lock If the long running process is CPU intensive, you should probably make it an independent process. 如果长时间运行的进程是CPU密集型的,那么您应该将其作为一个独立的进程。 If on the other hand, it's going to spend a lot of time blocking, then the GIL isn't really that big of a deal and you should be fine to make it a thread. 另一方面,如果它会花费大量的时间来阻止,那么GIL并不是那么大的交易,你应该把它变成一个线程。

Also, if you don't need something in particular that os.spawnle provides, consider using the multiprocessing package from the standard library. 此外,如果您不需要os.spawnle提供的特定os.spawnle ,请考虑使用标准库中的多处理包。 It provides an interface similar to that of the threading package and is altogether easier to use than mucking around with manually spawning and tracking processes. 它提供了类似于线程包的界面,并且比手动生成和跟踪过程更容易使用。

The obvious difference is that os.spawnle is used to start another process running a different program, whereas a thread would be executing code that's part of the same program. 明显的区别是os.spawnle用于启动另一个运行不同程序的进程,而一个线程将执行代码,该代码是同一程序的一部分。 In fact, if your background process is some other program that already exists, then os.spawnle (or some other means of creating a separate process) is your only option; 事实上,如果你的后台进程是已经存在的其他程序,那么os.spawnle (或其他一些创建单独进程的方法)是你唯一的选择; two threads in a program have to be running the same program. 程序中的两个线程必须运行相同的程序。

If you wondering whether you should structure your own code to be run as separate processes or as separate threads, then take a look at some of the process v. thread questions like this one to decide which better fits what you're trying to do. 如果您想知道是否应该将自己的代码构造为作为单独的进程或单独的线程运行,那么请查看一些像这样进程对线程问题,以确定哪个更适合您尝试执行的操作。 In particular, consider what resources the processes/threads will need to share, what they will communicate with each other, and how robust each needs to be -- a thread that crashes will bring the rest of the process down with it, for example. 特别是,考虑进程/线程需要共享哪些资源,它们将彼此通信的内容,以及每个需要的强大程度 - 例如,崩溃的线程将使其余的进程失效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM