简体   繁体   English

两个线程在Scala中访问同一文件

[英]Two threads accessing the same file in scala

I have a shell script that copies files into a location and another one that picks these up for further processing. 我有一个Shell脚本,可以将文件复制到一个位置,而另一个脚本可以将这些文件拾取以进行进一步处理。 I want to use multithreading to pick up files parallelly in Scala using a threadpool. 我想使用多线程在使用线程池的Scala中并行拾取文件。

However, if there are two threads and two files, both of them are picking up the same file. 但是,如果有两个线程和两个文件,则它们都将拾取同一文件。 I have tried the program a lot of times, and it always ends up like this. 我已经尝试过很多次了,但最终总是这样。 I need the threads to pick up different files in parallel . 我需要线程来并行拾取不同的文件

Can someone help me out? 有人可以帮我吗? What approaches can I use? 我可以使用什么方法? If you could point me in the right direction that would be enough. 如果您能指出正确的方向,那就足够了。

I think you can use a parallel sequence to do the processing in parallel. 我认为您可以使用并行序列并行进行处理。 You don't have to handle this logic yourself. 您不必自己处理此逻辑。 for ex. 对于前。 the code could be like this: 代码可能是这样的:

newFiles:Seq[String] = listCurrentFilesNames()
newFiles.par.foreach { fileName =>
   processFile(fileName)
}

This code will be executed in parallel. 此代码将并行执行。 and you could set the number of threads to a specific number as mentioned here: https://stackoverflow.com/a/37725987/2201566 并且您可以将线程数设置为此处提到的特定数: https : //stackoverflow.com/a/37725987/2201566

您还可以尝试使用演员-例如-供您参考-https: //github.com/tsheppard01/akka-parallel-read-csv-file

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

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