简体   繁体   English

跨程序/线程共享变量的最佳方法?

[英]Best way to share variables across programs/threads?

I currently have a program that runs an algorithm that processes real-time data, and once an hour a function is run that optimizes the parameters of the algorithm based on the new historical data. 我目前有一个程序,该程序运行可处理实时数据的算法,每小时运行一次功能,该功能可根据新的历史数据优化算法的参数。

Since this is running in a single thread, when the optimizer is running it pauses the real-time-data-processing algorithm, but it only takes about a minute so it's fine. 由于这是在单个线程中运行,因此当优化器运行时,它会暂停实时数据处理算法,但是只需要一分钟左右,所以还可以。

However, I want to greatly expand the optimizer and it's going to really increase the runtime. 但是,我想极大地扩展优化器,这将真正增加运行时间。 So I'm thinking of separating it into it's own program. 因此,我正在考虑将其分为自己的程序。 Then it'll run in its own thread and won't interrupt execution of the algorithm. 然后它将在自己的线程中运行,并且不会中断算法的执行。

To share the results of the optimizer with the algorithm, I guess I'll save them to a file each time the optimizer is run, and then the algorithm can periodically read the file. 为了与算法共享优化器的结果,我想我每次运行优化器时都会将它们保存到文件中,然后算法可以定期读取文件。

How would I ensure that the algorithm doesn't attempt to read this file at the same time as the optimizer is writing to it? 如何确保算法不会在优化程序写入文件的同时尝试读取该文件? Does the OS file system already not allow that? OS文件系统已经不允许这样做吗?

Also, is there a better way to share variables across different programs? 另外,是否有更好的方法在不同程序之间共享变量? Or maybe it would be better to split the optimizer off into a separate thread within the same program? 还是最好在同一程序中将优化器拆分为一个单独的线程? Any suggestions would be appreciated, thanks! 任何建议将不胜感激,谢谢!

first of all to share variables between programs you have to consider using named pipes. 首先,必须在使用命名管道的程序之间共享变量。

If you want to use anything other than a named pipe, maybe just an ordinary file you have to handle race condition or reading wrong data from the file, you have to implement a lock mechanism, maybe a lockfile, if you are about to write to the file, you create a lock file, the routine that reads the file will check for the existence of the lock file, if the lock file exists it won't read from it, when the routine that writes to the file is done, you can remove it. 如果要使用命名管道以外的其他任何东西(可能只是普通文件,则必须处理竞争条件或从文件中读取错误数据),则必须实现锁机制,如果要写入的内容可能是锁文件。该文件后,您将创建一个锁定文件,读取该文件的例程将检查该锁定文件是否存在,如果该锁定文件存在,则不会从该文件中读取该文件,当写入该文件的例程完成时,您可以删除它。

You can also use the cluster module , you can easily communicate between two process ( child and parent ) without creating a file. 您还可以使用cluster模块,可以轻松地在两个进程(子进程和父进程)之间进行通信,而无需创建文件。

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

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