Difference between revisions of "Multi-threading: A brief introduction(多线程简介)"

From wiki.visual-prolog.com

Line 3: Line 3:
只有 ''商业版'' 才支持多线程应用。
只有 ''商业版'' 才支持多线程应用。


Threads are represented by the <vp>thread</vp> class/interface.  And it is very simple to create a new thread:
线程是由 <vp>thread</vp> /接口表示的。创建一个新线程很简单:


<vip>clauses
<vip>clauses
         ...
         ...
         T = thread::start(myThread), % start a new thread which executes the predicate myThread
         T = thread::start(myThread), % 启动一个新线程,这个线程执行谓词 myThread
         ...
         ...



Revision as of 02:15, 22 June 2015

(以下内容译自Category:Tutorials中的Multi-threading: A brief introduction。)

只有 商业版 才支持多线程应用。

线程是由 thread 类/接口表示的。创建一个新线程很简单:

clauses
        ...
        T = thread::start(myThread), % 启动一个新线程,这个线程执行谓词 myThread
        ...
 
predicates
    myThread : ().
clauses
   myThread() :-
        ...

Using anonymous predicates it is also very simple to transfer data to the new thread:

clauses
        ...
        SomeData = ...,
        T = thread::start( { :- myThreadWithData(SomeData) }),
        ...
 
predicates
    myThreadWithData : (complexData ThreadInputData).
clauses
   myThreadWithData(ThreadInputData) :-
        ...

You can wait for thread termination, because a thread object is a synchronization object:

clauses
        ...
        SomeData = ...,
        T = thread::start( { :- myThreadWithData(SomeData) } ),
        ... % stuff done in parallel with T
        T:wait(),  % Wait for T to terminate
        ...

Thread safe acces to shared data can be done using monitors and/or synchronization objects like criticalSection, event, mutex and semaphore.

参考

Thread safety in Visual Prolog