Julia 中的异步编程
Asynchrounous programming in Julia
我有一个在 Julia 中实现的 Aho-Corasick 算法。我想查看文件中的 100 万个单词并将我的 Aho 函数应用于它们以查看文件中是否出现了一个单词。我如何在 Julia 中异步执行此操作?我最初的想法是生成我的 Aho 函数的多个实例,每个实例都查看文件的特定部分。一旦其中一个 returns 为真,我就退出。我不太熟悉 Julia,所以我想知道我应该了解该语言的哪些功能。
下面将对字典中的单词进行线程搜索,每个单词一个线程。您需要将 1000000 字的文件读入内存才能这样做。
function foreachword(wordfile::String, condition::Function)
words = split(read(wordfile, String), r"\s+")
continuecondition = Threads.Atomic{Bool}(true)
@Threads.threads for word in words
if continuecondition[] && condition(word)
println("word found")
continuecondition[] = false # loop will run on all, but not do the potentially expensive call any more
end
end
end
iscalliope(w) = w == "calliope"
foreachword("unixdict.txt", iscalliope)
您也可以(参见下面的评论)对文件的片段进行拆分(允许将一个词一分为二的片段):
function foreachchunk(wordfile::String, condition::Function, maxwordlength=30)
fsize = stat(wordfile).size
chunksize = fsize ÷ Threads.nthreads()
text = read(wordfile, String)
continuecondition = Threads.Atomic{Bool}(true)
@Threads.threads for start in 1:chunksize:fsize-chunksize
segment = @view text[start : min(fsize, start + chunksize + maxwordlength)]
words = split(segment, r"\s+")
for word in words
continuecondition[] || break
if condition(word)
println("word found")
continuecondition[] = false
end
end
end
end
foreachchunk("unixdict.txt", iscalliope)
我有一个在 Julia 中实现的 Aho-Corasick 算法。我想查看文件中的 100 万个单词并将我的 Aho 函数应用于它们以查看文件中是否出现了一个单词。我如何在 Julia 中异步执行此操作?我最初的想法是生成我的 Aho 函数的多个实例,每个实例都查看文件的特定部分。一旦其中一个 returns 为真,我就退出。我不太熟悉 Julia,所以我想知道我应该了解该语言的哪些功能。
下面将对字典中的单词进行线程搜索,每个单词一个线程。您需要将 1000000 字的文件读入内存才能这样做。
function foreachword(wordfile::String, condition::Function)
words = split(read(wordfile, String), r"\s+")
continuecondition = Threads.Atomic{Bool}(true)
@Threads.threads for word in words
if continuecondition[] && condition(word)
println("word found")
continuecondition[] = false # loop will run on all, but not do the potentially expensive call any more
end
end
end
iscalliope(w) = w == "calliope"
foreachword("unixdict.txt", iscalliope)
您也可以(参见下面的评论)对文件的片段进行拆分(允许将一个词一分为二的片段):
function foreachchunk(wordfile::String, condition::Function, maxwordlength=30)
fsize = stat(wordfile).size
chunksize = fsize ÷ Threads.nthreads()
text = read(wordfile, String)
continuecondition = Threads.Atomic{Bool}(true)
@Threads.threads for start in 1:chunksize:fsize-chunksize
segment = @view text[start : min(fsize, start + chunksize + maxwordlength)]
words = split(segment, r"\s+")
for word in words
continuecondition[] || break
if condition(word)
println("word found")
continuecondition[] = false
end
end
end
end
foreachchunk("unixdict.txt", iscalliope)