简体   繁体   English

Python线程处理-如何知道线程是否已在运行?

[英]Python threading — How to know if thread already is running?

I have a thread I use to process data. 我有一个用于处理数据的线程。 Right now it triggers every time it detects a new file in a folder. 现在,它每次在文件夹中检测到新文件时都会触发。 I am coding in Python, but maybe it is more of a general programming question? 我使用Python进行编码,但也许更多是一个通用的编程问题?

My question is two-fold: 我的问题有两个:

  1. Should I use a trigger like that (event-driven, more or less), or should I be using time based (every 3 minutes, create a new thread)? 我应该使用这样的触发器(事件驱动,或多或少),还是应该使用基于时间的触发器(每3分钟创建一个新线程)?

  2. If I go with time-based and create a new thread, wouldn't it cause problems if the two threads are processing the same data? 如果我使用基于时间的方法并创建一个新线程,那么如果两个线程正在处理相同的数据,这不会引起问题吗? Is there a way to tell them to work together or to not spawn a second one if one exists? 有没有办法告诉他们一起工作,或者如果存在的话不催生第二个?

I apologize for the probable naivety of my question, I am still quite new to multi-threading and mutliple processes, so I still don't know when to use what. 对于这个问题的天真性,我深表歉意。对于多线程和多进程,我还是很陌生,所以我仍然不知道何时使用什么。

As far as I understand you process any new file with a separate thread, so it behaves like a server processing multiple requests with a single routine. 据我了解,您使用单独的线程处理任何新文件,因此它的行为就像服务器使用一个例程处理多个请求一样。

1) I think that time-triggered creation isn't good in your case because it doesn't depend on either system performance or number of files to process. 1)我认为时间触发的创建在您的情况下效果不佳,因为它不依赖于系统性能或要处理的文件数。 You may run a few threads as daemons and have a main thread that assign tasks to these threads as soon as they come. 您可以将几个线程作为守护程序运行,并具有一个主线程,这些线程在任务出现时立即将其分配给这些线程。 If there are too many at the same time, you just drop new tasks. 如果同时有太多任务,则只需删除新任务。 On the other hand, you may create a new thread that does processing each time new file appears and then join it when the processing has finished 另一方面,您可以创建一个新线程,该线程在每次出现新文件时都会进行处理,然后在处理完成后将其join

2) You may start new thread explicitly giving it the file name. 2)您可以显式启动新线程,并为其指定文件名。 Whether it's possible or not for a few threads to work with a single file simultaneously would depend on what you exactly do with the file. 几个线程是否可以同时使用一个文件,将取决于您对文件的处理方式。 In general it becomes way more complicated than single file per thread 通常,它变得比每个线程单个文件更复杂

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

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