4,493
edits
m (Text replacement - "</source>" to "</syntaxhighlight>") |
m (Text replacement - "<source" to "<syntaxhighlight") |
||
Line 3: | Line 3: | ||
== Usage == | == Usage == | ||
Spawn is used to run background tasks, for example for monitoring or handling incoming requests. Since the thread number is returned, < | Spawn is used to run background tasks, for example for monitoring or handling incoming requests. Since the thread number is returned, <syntaxhighlight lang=apl inline>⎕TSYNC</syntaxhighlight> ("Thread Synchronise") is provided to retrieve the result, given the thread number. If the result is ready before <syntaxhighlight lang=apl inline>⎕TSYNC</syntaxhighlight> is used, it prints to the [[session]] if applicable. | ||
Spawn is often used in conjunction with the [[Each]] operator (< | Spawn is often used in conjunction with the [[Each]] operator (<syntaxhighlight lang=apl inline>¨</syntaxhighlight>) to launch multiple threads in parallel. | ||
As Spawn is an operator, it cannot be directly used with a [[niladic function]], since a niladic function is called immediately when its name is referenced. As a workaround, the niladic function can be wrapped in a [[dfn]] and called with a dummy argument: < | As Spawn is an operator, it cannot be directly used with a [[niladic function]], since a niladic function is called immediately when its name is referenced. As a workaround, the niladic function can be wrapped in a [[dfn]] and called with a dummy argument: <syntaxhighlight lang=apl inline>{nilFun}&⍬</syntaxhighlight> | ||
== Examples == | == Examples == | ||
< | <syntaxhighlight lang=apl> | ||
÷&4 ⍝ Reciprocal in background | ÷&4 ⍝ Reciprocal in background | ||
0.25 | 0.25 | ||
Line 18: | Line 18: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
{{Works in|[[Dyalog APL]]}} | {{Works in|[[Dyalog APL]]}} | ||
The effect of running code in the background can be observed when a measurable amount of time elapses. In the first expression below, get the current time (in milliseconds) and then [[delay]] (< | The effect of running code in the background can be observed when a measurable amount of time elapses. In the first expression below, get the current time (in milliseconds) and then [[delay]] (<syntaxhighlight lang=apl inline>⎕DL</syntaxhighlight>) for each of 1, 2, and 3 seconds, eventually computing the elapsed time, which is slightly more than 1+2+3 seconds (6000 milliseconds). In the second expression, the delaying threads are launched, but we don't await their completion before computing the elapsed time. In the final expression, we synchronise the parallel running delays, giving us a total elapsed time only slightly longer than the longest delay. | ||
< | <syntaxhighlight lang=apl> | ||
t←⎕AI[3] ⋄ ⎕DL¨⍳3 ⋄ ⎕AI[3]-t | t←⎕AI[3] ⋄ ⎕DL¨⍳3 ⋄ ⎕AI[3]-t | ||
6138 | 6138 |