本文介绍了Lua:Lua中具有线程状结构的抢占式(非合作式)多任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Lua是否内置任何抢先式多任务处理功能.我想在我的多核系统上使用并发线程.

我调查了协程(请参阅lua-users.org/wiki/CoroutinesTutorial和stackoverflow.com/questions/3107165/那里是一种命名为lua的线程的方法,有人知道吗? ),但似乎不符合要求.我写了以下代码:



程序打印:



,然后卡住.我怀疑它只是在无限循环中等待.用gdb附加它可以发现只有一个线程在运行.

我怀疑协程是协作式多任务处理,对吗?

如果是这样,是否有本地的Lua方法在Lua中具有线程?

如果没有,我是否必须使用其他库(例如www.inf.puc-rio.br/~roberto/docs/ry08-05.pdf [PDF]或kotisivu.dnainternet.net/askok/bin/lanes /)?

谢谢,托尼

解决方案

协程确实是合作的,如卢阿书. ANSI C不解决线程问题,因此在Lua中没有本机"方法来执行抢占式多线程,就像在C中没有本机"方法那样.相反,您必须依赖对基础操作的调用系统. Lua Wiki 讨论了两种维护线程状态的方法.我还发现了有关协程的博客帖子详细介绍了这两种方法之一(尽管他本人并没有参与抢占式线程处理).

值得一提的是Lua的书说:我们认为多线程不是Lua的好主意."如果您愿意,可以在第30章中详细了解他们的担忧.

I was wondering whether Lua has any preemptive multitasking facilities built-in. I would like to have concurrent threads to use on my multi-core system.

I looked into coroutines (see lua-users.org/wiki/CoroutinesTutorial and stackoverflow.com/questions/3107165/there-is-a-type-named-thread-in-lua-does-anyone-know-something-of-this), but it seems not to fit the bill. I wrote the following code:


function foo(ver)
    local iter = 1;
    while true do
        print("foo ver="..ver.." iter="..iter);
        iter = iter + 1;
        for ii = 1,100000 do end -- busy wait
        coroutine.yield()
     end
end

co1 = coroutine.create(foo)
co2 = coroutine.create(foo)

coroutine.resume(co1, 1)
coroutine.resume(co2, 2)

while true do end -- infinite loop


The program prints:


foo ver=1 iter=1
foo ver=2 iter=1


and then gets stuck. I suspect it just waits in the infinite loop. Attaching to it with gdb reveals that there is only one thread running.

I suspect coroutines are cooperative multitasking, correct?

If so, is there a native, Lua way to have threads in Lua?

If not, do I have to use other libraries (like www.inf.puc-rio.br/~roberto/docs/ry08-05.pdf [PDF] or kotisivu.dnainternet.net/askok/bin/lanes/)?

Thanks,Tony

解决方案

Coroutines are indeed cooperative, as stated in the Lua book. ANSI C does not address threading, so there is no "native" way to do preemptive multithreading in Lua just as there is no "native" way to do so in C. Instead, you'll have to rely on calls to the underlying operating system. The Lua wiki discusses two ways of maintaining thread state. I also found a blog post about coroutines that goes into more detail on one of the two methods (though he doesn't himself get into preemptive threading).

It might also be worth noting that the Lua book says, "we do not think multithreading is a good idea for Lua." You can read more about their concerns in chapter 30 if you're so inclined.

这篇关于Lua:Lua中具有线程状结构的抢占式(非合作式)多任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:34