简体   繁体   English

Python 列表的单独线程,在时间限制后自动删除

[英]Python Seperate thread for list which automatically removes after time limit

I want to have a list which my main process will add data to and this seperate thread will see the data added, wait a set amount of eg 1 minute then remove it from the list.我想要一个列表,我的主进程将向其中添加数据,这个单独的线程将看到添加的数据,等待一定的时间,例如 1 分钟,然后将其从列表中删除。 Im not very experience with multi-threading in python so i dont know how to do this.我对 python 中的多线程不是很有经验,所以我不知道该怎么做。

The way you could achieve this is by using a global variable as your list, as your thread will be able to access data from it.实现此目的的方法是使用全局变量作为列表,因为您的线程将能够从中访问数据。 You can use a deque from the collections library, and each time you add something in the queue, you spawn a new thread that will just pop from the front after waiting that set amount of time.您可以使用 collections 库中的双端队列,每次在队列中添加内容时,都会生成一个新线程,该线程将在等待设定的时间后从前面弹出。

Although, you have to be careful with the race conditions.虽然,你必须小心比赛条件。 It may happen that you try to write something at one end in your main thread and at the same time erase something from the beginning in one of your new threads, and this will cause unexpected behavior.您可能会尝试在主线程的一端写一些东西,同时在一个新线程中从头开始擦除一些东西,这会导致意外的行为。

Best way to avoid this is by using a lock.避免这种情况的最好方法是使用锁。

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

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