40 Commits
Author SHA1 Message Date
server c2aa449a65 Merge pull request #26 from rayaman/V15.1.0
V15.1.0
2021-11-30 21:28:18 -05:00
server 57563688ae fixed a bug 2021-11-30 21:23:45 -05:00
server 317dacd0de Updated readme and documentation 2021-11-30 20:54:54 -05:00
server a7ba146a64 Cleaning up code, fixing bugs (Almost ready for release) 2021-11-30 20:11:20 -05:00
server efa30e30cc Updated changes, connections can be added 2021-11-27 17:55:13 -05:00
server 197b418fc5 Fixed typo 2021-10-10 09:12:42 -04:00
server d3d53599f7 function's are now callable objects 2021-10-10 09:10:24 -04:00
server bf517facd1 Adding features to threaded functions 2021-07-19 17:04:43 -04:00
server 9cff2735ba threaded functions can now be paused 2021-07-05 22:23:45 -04:00
server ea77b934b6 Updated version number 2021-07-02 21:13:47 -04:00
server 74bfd571a5 Rockspecs/Readme Updated 2021-07-02 16:57:58 -04:00
server 06132fc1dd Fixed rockspec for threading.lua, tweaking code 2021-07-02 15:46:37 -04:00
server ade5172f26 Renamed lovr to lovrManager to fit theme 2021-06-24 23:11:10 -04:00
server bdc657771d Changelog/Documentation updated. Processors added 2021-06-24 23:09:15 -04:00
server 8c24bcbbb0 Modified changes.md 2021-06-19 21:09:32 -04:00
server 804a117ed0 Fixed return bug 2021-06-19 20:12:06 -04:00
server 37afd37f9e Adding tests wip 2021-05-27 16:47:45 -04:00
server 4399fb6424 updated readme 2021-05-02 22:31:29 -04:00
server 02a54e13ea Started to work on lovr integration 2021-05-02 22:26:35 -04:00
server bb2c7d6440 Merge pull request #20 from rayaman/V15.1.0
Fixed issue with lightloop not triggering the preload event
2021-05-02 22:04:54 -04:00
server d1b8ed1922 Fixed issue with lightloop not triggering the preload event 2021-05-02 22:04:25 -04:00
server 9992a2c091 Merge pull request #19 from rayaman/v15.0.0
V15.0.0
2021-05-01 17:33:58 -04:00
server 155466dc71 Merge branch 'master' into v15.0.0 2021-05-01 17:33:23 -04:00
server cea6508d68 Release ready 2021-05-01 17:31:14 -04:00
server 726707eb8a Modifying rockspec 2021-05-01 16:35:31 -04:00
server 9a9d28f62f Cleaning up... 2021-05-01 16:21:34 -04:00
server ed924a3d9d Version 15.0.0 2021-05-01 15:52:32 -04:00
server 2d239c65ea tests 2021-04-30 10:48:58 -04:00
server fd8e77555a Testing something 2021-04-30 10:00:13 -04:00
server b60aab9602 Will be coming back to this project
Plan on finally getting back to working on the network parallelism.
2021-04-29 15:34:13 -04:00
server 180176e2cf Updated License date 2021-04-03 12:40:33 -04:00
server 952b592b97 Update README.md
fixed typo
2020-12-24 12:38:07 -05:00
server d2ce7e070b Fixing pseudothreading 2020-05-15 01:38:24 -04:00
server 300827b7bd cleaning up 2020-05-08 17:44:16 -04:00
server 9d97eac146 Working on psuedo threading 2020-05-08 11:41:52 -04:00
server 61dcb9da01 Working on 15.0.0 2020-03-29 11:50:15 -04:00
server b597fbdf9b removed okd files 2020-03-14 20:21:08 -04:00
server 8fbaa76fe9 removed old files 2020-03-14 20:16:45 -04:00
server abb3da416f Merge pull request #18 from rayaman/v14.2.0
v14.2.0 release ready
2020-03-14 09:13:57 -04:00
server 8ba489dc58 Merge pull request #17 from rayaman/v14.2.0
V14.2.0
2020-03-14 08:35:29 -04:00
31 changed files with 2850 additions and 540 deletions
+1
View File
@@ -2,6 +2,7 @@
test2.lua test2.lua
*.mp3 *.mp3
*.exe *.exe
*.dll
lanestestclient.lua lanestestclient.lua
lanestest.lua lanestest.lua
sample-node.lua sample-node.lua
-50
View File
@@ -1,50 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "launch-lua",
"type": "lua",
"request": "launch",
"workingDirectory": "${workspaceRoot}",
"sourceBasePath": "${workspaceRoot}",
"executable": "C:\\Program Files (x86)\\Lua\\5.1\\lua.exe",
"arguments": "main.lua",
"listenPublicly": false,
"listenPort": 56789,
"encoding": "UTF-8",
"env": {}
},
{
"name": "launch-gideros",
"type": "lua",
"request": "launch",
"workingDirectory": "${workspaceRoot}",
"giderosPath": "C:/Program Files (x86)/Gideros",
"gprojPath": "${workspaceRoot}/GPROJ.gproj",
"jumpToGiderosErrorPosition": false,
"stopGiderosWhenDebuggerStops": true,
"listenPublicly": false,
"listenPort": 56789,
"encoding": "UTF-8"
},
{
"name": "wait",
"type": "lua",
"request": "attach",
"workingDirectory": "${workspaceRoot}",
"sourceBasePath": "${workspaceRoot}",
"listenPublicly": false,
"listenPort": 56789,
"encoding": "UTF-8"
},
{
"type": "lua",
"request": "launch",
"name": "Launch",
"program": "${workspaceFolder}/test.lua"
}
]
}
+263 -45
View File
@@ -1,8 +1,10 @@
Current Multi Version: 14.2.0 Current Multi Version: 15.1.0
# Multi static variables # Multi static variables
`multi.Version` — The current version of the library `multi.Version` — The current version of the library
`multi.TIMEOUT` — The value returned when a timed method times out
`multi.Priority_Core` — Highest level of pirority that can be given to a process `multi.Priority_Core` — Highest level of pirority that can be given to a process
</br>`multi.Priority_Very_High` </br>`multi.Priority_Very_High`
</br>`multi.Priority_High` </br>`multi.Priority_High`
@@ -14,12 +16,80 @@ Current Multi Version: 14.2.0
</br>`multi.Priority_Idle` — Lowest level of pirority that can be given to a process </br>`multi.Priority_Idle` — Lowest level of pirority that can be given to a process
# Multi Runners # Multi Runners
`multi:lightloop()` — A light version of the mainloop `multi:lightloop()` — A light version of the mainloop doesn't run Coroutine based threads
</br>`multi:loveloop([BOOLEAN: light true])` — Run's all the love related features as well </br>`multi:loveloop([BOOLEAN: light true])` — Run's all the love related features as well
</br>`multi:mainloop([TABLE settings])` — This runs the mainloop by having its own internal while loop running </br>`multi:mainloop([TABLE settings])` — This runs the mainloop by having its own internal while loop running
</br>`multi:threadloop([TABLE settings])` — This runs the mainloop by having its own internal while loop running, but prioritizes threads over multi-objects </br>`multi:threadloop([TABLE settings])` — This runs the mainloop by having its own internal while loop running, but prioritizes threads over multi-objects
</br>`multi:uManager([TABLE settings])` — This runs the mainloop, but does not have its own while loop and thus needs to be within a loop of some kind. </br>`multi:uManager([TABLE settings])` — This runs the mainloop, but does not have its own while loop and thus needs to be within a loop of some kind.
# Global Methods
`multi:init()` — Uesd to initiate the library, should only be called once
`multi.getCurrentProcess()` — Returns currently running Process
`multi.`
# Processor Methods
These methods can be called either on the multi namespace or a process returned by `proc = multi:newProcessor()`
`proc.Stop()` — Stops the main process/child process. **Note:** If the main process is stopped all child processes are stopped as well
`proc:getTasksDetails([STRING: displaytype])` — Gets a table or string of all the running tasks
Processor Attributes
---
| Attribute | Type | Returns | Description |
---|---|---|---
Start|Method()|self| Starts the process
Stop|Method()|self| Stops the process
OnError|Connection|connection| Allows connection to the process error handler
Type|Member:`string`|"process"| Contains the type of object
Active|Member:`boolean`|variable| If false the process is not active
Name|Member:`string`|variable| The name set at process creation
process|Thread|thread| A handle to a multi thread object
[Refer to the objects for more methods](#non-actors)
Example:
```lua
package.path = "./?/init.lua;"..package.path
multi,thread = require("multi"):init()
-- Create a processor object, it works a lot like the multi object
sandbox = multi:newProcessor()
-- On our processor object create a TLoop that prints "testing..." every second
sandbox:newTLoop(function()
print("testing...")
end,1)
-- Create a thread on the processor object
sandbox:newThread("Test Thread",function()
-- Create a counter named 'a'
local a = 0
-- Start of the while loop that ends when a = 10
while true do
-- pause execution of the thread for 1 second
thread.sleep(1)
-- increment a by 1
a = a + 1
-- display the name of the current process
print("Thread Test: ".. multi.getCurrentProcess().Name)
if a == 10 then
-- Stopping the processor stops all objects created inside that process including threads. In the backend threads use a regular multiobject to handle the scheduler and all of the holding functions. These all stop when a processor is stopped. This can be really useful to sandbox processes that might need to turned on and off with ease and not having to think about it.
sandbox.Stop()
end
end
-- Catch any errors that may come up
end).OnError(function(...)
print(...)
end)
sandbox.Start() -- Start the process
multi:mainloop() -- The main loop that allows all processes to continue
```
# Multi Settings # Multi Settings
**Note:** Most settings have been fined tuned to be at the peak of performance already, however preLoop, protect (Which drastically lowers preformance), and stopOnError should be used freely to fit your needs. **Note:** Most settings have been fined tuned to be at the peak of performance already, however preLoop, protect (Which drastically lowers preformance), and stopOnError should be used freely to fit your needs.
@@ -150,10 +220,13 @@ returns or nil
The connect feature has some syntax sugar to it as seen below The connect feature has some syntax sugar to it as seen below
- `link = conn(FUNCTION func, [STRING name nil], [NUMBER #conns+1])` - `link = conn(FUNCTION func, [STRING name nil], [NUMBER #conns+1])`
- `combinedconn = conn1 + conn2` — A combined connection is triggered when all connections are triggered. See example [here](#coroutine-based-threading-cbt)
Example: Example:
```lua ```lua
local multi = require("multi") multi,thread = require("multi"):init()
-- Lets create the events -- Lets create the events
yawn={} yawn={}
OnCustomSafeEvent=multi:newConnection(true) -- lets pcall the calls in case something goes wrong default OnCustomSafeEvent=multi:newConnection(true) -- lets pcall the calls in case something goes wrong default
@@ -201,7 +274,7 @@ Timeouts are a collection of methods that allow you to handle timeouts. These on
```lua ```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
multi = require("multi") multi,thread = require("multi"):init()
loop = multi:newLoop(function() loop = multi:newLoop(function()
-- do stuff -- do stuff
@@ -224,7 +297,7 @@ loop:OnTimerResolved(function(self,...)
print(...) print(...)
end) end)
multi:lightloop() multi:mainloop()
``` ```
As mentioned above this is made much easier using threads As mentioned above this is made much easier using threads
```lua ```lua
@@ -255,14 +328,14 @@ print(func(0))
Example: Example:
```lua ```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
multi = require("multi") multi,thread = require("multi"):init()
multi:scheduleJob({min = 30},function() -- Every hour at minute 30 this event will be triggered! You can mix and match as well! multi:scheduleJob({min = 30},function() -- Every hour at minute 30 this event will be triggered! You can mix and match as well!
print("Hi") print("Hi")
end) end)
multi:scheduleJob({min = 30,hour = 0},function() -- Every day at 12:30AM this event will be triggered multi:scheduleJob({min = 30,hour = 0},function() -- Every day at 12:30AM this event will be triggered
print("Hi") print("Hi")
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Universal Actor methods # Universal Actor methods
@@ -287,7 +360,7 @@ All of these functions are found on actors
Example: Example:
```lua ```lua
local multi = require("multi") multi,thread = require("multi"):init()
count=0 count=0
-- A loop object is used to demostrate how one could use an event object. -- A loop object is used to demostrate how one could use an event object.
loop=multi:newLoop(function(self,dt) loop=multi:newLoop(function(self,dt)
@@ -298,7 +371,7 @@ event:OnEvent(function(self) -- connect to the event object
loop:Destroy() -- destroys the loop from running! loop:Destroy() -- destroys the loop from running!
print("Stopped that loop!",count) print("Stopped that loop!",count)
end) -- events like alarms need to be reset the Reset() command works here as well end) -- events like alarms need to be reset the Reset() command works here as well
multi:lightloop() multi:mainloop()
``` ```
# Actor: Updaters # Actor: Updaters
@@ -311,12 +384,12 @@ Updaters are a mix between both loops and steps. They were a way to add basic pr
Example: Example:
```lua ```lua
local multi = require("multi") multi,thread = require("multi"):init()
updater=multi:newUpdater(5000) -- simple, think of a loop with the skip feature of a step updater=multi:newUpdater(5000) -- simple, think of a loop with the skip feature of a step
updater:OnUpdate(function(self) updater:OnUpdate(function(self)
print("updating...") print("updating...")
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Actor: Alarms # Actor: Alarms
@@ -328,13 +401,13 @@ Alarms ring after a certain amount of time, but you need to reset the alarm ever
Example: Example:
```lua ```lua
local multi = require("multi") multi,thread = require("multi"):init()
alarm=multi:newAlarm(3) -- in seconds can go to .001 uses the built in os.clock() alarm=multi:newAlarm(3) -- in seconds can go to .001 uses the built in os.clock()
alarm:OnRing(function(a) alarm:OnRing(function(a)
print("3 Seconds have passed!") print("3 Seconds have passed!")
a:Reset(n) -- if n were nil it will reset back to 3, or it would reset to n seconds a:Reset(n) -- if n were nil it will reset back to 3, or it would reset to n seconds
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Actor: Loops # Actor: Loops
@@ -346,7 +419,7 @@ Loops are events that happen over and over until paused. They act like a while l
Example: Example:
```lua ```lua
package.path="?/init.lua;?.lua;"..package.path package.path="?/init.lua;?.lua;"..package.path
local multi = require("multi") multi,thread = require("multi"):init()
local a = 0 local a = 0
loop = multi:newLoop(function() loop = multi:newLoop(function()
a = a + 1 a = a + 1
@@ -355,7 +428,7 @@ loop = multi:newLoop(function()
loop:Pause() loop:Pause()
end end
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Actor: TLoops # Actor: TLoops
@@ -366,7 +439,7 @@ multi:lightloop()
Example: Example:
```lua ```lua
package.path="?/init.lua;?.lua;"..package.path package.path="?/init.lua;?.lua;"..package.path
local multi = require("multi") multi,thread = require("multi"):init()
local a = 0 local a = 0
loop = multi:newTLoop(function() loop = multi:newTLoop(function()
a = a + 1 a = a + 1
@@ -375,7 +448,7 @@ loop = multi:newTLoop(function()
loop:Pause() loop:Pause()
end end
end,1) end,1)
multi:lightloop() multi:mainloop()
``` ```
# Actor: Steps # Actor: Steps
@@ -390,13 +463,13 @@ multi:lightloop()
Example: Example:
```lua ```lua
package.path="?/init.lua;?.lua;"..package.path package.path="?/init.lua;?.lua;"..package.path
local multi = require("multi") multi,thread = require("multi"):init()
multi:newStep(1,10,1,0):OnStep(function(step,pos) multi:newStep(1,10,1,0):OnStep(function(step,pos)
print(step,pos) print(step,pos)
end):OnEnd(fucntion(step) end):OnEnd(fucntion(step)
step:Destroy() step:Destroy()
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Actor: TSteps # Actor: TSteps
@@ -411,13 +484,13 @@ multi:lightloop()
Example: Example:
```lua ```lua
package.path="?/init.lua;?.lua;"..package.path package.path="?/init.lua;?.lua;"..package.path
local multi = require("multi") multi,thread = require("multi"):init()
multi:newTStep(1,10,1,1):OnStep(function(step,pos) multi:newTStep(1,10,1,1):OnStep(function(step,pos)
print(step,pos) print(step,pos)
end):OnEnd(fucntion(step) end):OnEnd(fucntion(step)
step:Destroy() step:Destroy()
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Coroutine based Threading (CBT) # Coroutine based Threading (CBT)
@@ -425,7 +498,23 @@ Helpful methods are wrapped around the builtin coroutine module which make it fe
**threads.\* used within threaded enviroments** **threads.\* used within threaded enviroments**
- `thread.sleep(NUMBER n)` — Holds execution of the thread until a certain amount of time has passed - `thread.sleep(NUMBER n)` — Holds execution of the thread until a certain amount of time has passed
- `VARIABLE returns = thread.hold(FUNCTION func)` — Hold execution until the function returns non nil. All returns are passed to the thread once the conditions have been met. To pass nil use `multi.NIL`\* - `VARIABLE val = THREAD.hold(FUNCTION|CONNCETION|NUMBER func, TABLE options)` — Holds the current thread until a condition is met
| Option | Description |
---|---
| interval | Time between each poll |
| cycles | Number of cycles before timing out |
| sleep | Number of seconds before timing out |
| skip | Number of cycles before testing again, does not cause a timeout! |
**Note:** cycles and sleep options cannot both be used at the same time. Interval and skip cannot be used at the same time either. Cycles take priority over sleep if both are present! HoldFor and HoldWithin can be emulated using the new features. Old functions will remain for backward compatibility.
Using cycles, sleep or interval will cause a timeout; returning nil, multi.TIMEOUT
`func` can be a number and `thread.hold` will act like `thread.sleep`. When `func` is a number the option table will be ignored!
`func` can be a connection and will hold until the condition is triggered. When using a connection the option table is ignored!
- `thread.skip(NUMBER n)` — How many cycles should be skipped until I execute again - `thread.skip(NUMBER n)` — How many cycles should be skipped until I execute again
- `thread.kill()` — Kills the thread - `thread.kill()` — Kills the thread
- `thread.yeild()` — Is the same as using thread.skip(0) or thread.sleep(0), hands off control until the next cycle - `thread.yeild()` — Is the same as using thread.skip(0) or thread.sleep(0), hands off control until the next cycle
@@ -438,9 +527,64 @@ Helpful methods are wrapped around the builtin coroutine module which make it fe
- `th = thread.getRunningThread()` — Returns the currently running thread - `th = thread.getRunningThread()` — Returns the currently running thread
- `VARIABLE returns or nil, "TIMEOUT" = thread.holdFor(NUMBER: sec, FUNCTION: condition)` — Holds until a condidtion is met, or if there is a timeout nil,"TIMEOUT" - `VARIABLE returns or nil, "TIMEOUT" = thread.holdFor(NUMBER: sec, FUNCTION: condition)` — Holds until a condidtion is met, or if there is a timeout nil,"TIMEOUT"
- `VARIABLE returns or nil, "TIMEOUT" = thread.holdWithin(NUMBER: skip, FUNCTION: func)` — Holds until a condition is met or n cycles have happened. - `VARIABLE returns or nil, "TIMEOUT" = thread.holdWithin(NUMBER: skip, FUNCTION: func)` — Holds until a condition is met or n cycles have happened.
- `returns or handler = thread:newFunction(FUNCTION: func, [BOOLEAN: holdme false])` — func: The function you want to be threaded. holdme: If true the function waits until it has returns and then returns them. Otherwise the function returns a table - `func = thread:newFunction(FUNCTION: func, [BOOLEAN: holdme false])` — func: The function you want to be threaded. holdme: If true the function waits until it has returns and then returns them. Otherwise the function returns a table
- `handler.connect(Function: func(returns))` — Connects to the event that is triggered when the returns are avaiable - `func:Pause()` — Pauses a function, function will return `nil`, `"Function is paused"`
- `VARIAABLE returns = handler.wait()` — Waits until returns are avaiable and then returns them - `func:Resume()` — Resumes a paused function
- `func:holdMe(BOOLEAN: set)` — Sets the holdme argument to `set`
- `handler = func(VARIABLE args)` — Calls the function, will return
- `handler.isTFunc` — if true then its a threaded function
- `handler.wait()` — waits for the function to finish and returns like normal
- `handler.connect(Function: func(returns))` — Connects to the event that is triggered when the returns are avaiable and returns them
- `VARIABLE returns = handler.wait()` — Waits until returns are avaiable and then
- `handler.OnStatus(connector(VARIABLE args))` — A connection to the running function's status see example below
- `handler.OnReturn(connector(VARIABLE args))` — A connection that is triggered when the running function is finished see example below
- `handler.OnError(connector(nil,error))`
Example:
```lua
package.path = "./?/init.lua;"..package.path
multi,thread = require("multi"):init()
func = thread:newFunction(function(count)
local a = 0
while true do
a = a + 1
thread.sleep(.1)
thread.pushStatus(a,count)
if a == count then break end
end
return "Done"
end)
multi:newThread("Function Status Test",function()
local ret = func(10)
local ret2 = func(15)
local ret3 = func(20)
ret.OnStatus(function(part,whole)
--[[ Print out the current status. In this case every second it will update with:
10%
20%
30%
...
100%
Function Done!
]]
print(math.ceil((part/whole)*1000)/10 .."%")
end)
ret2.OnStatus(function(part,whole)
print("Ret2: ",math.ceil((part/whole)*1000)/10 .."%")
end)
ret3.OnStatus(function(part,whole)
print("Ret3: ",math.ceil((part/whole)*1000)/10 .."%")
end)
-- Connections can now be added together, if you had multiple holds and one finished before others and wasn't consumed it would lock forever! This is now fixed
thread.hold(ret2.OnReturn + ret.OnReturn + ret3.OnReturn)
print("Function Done!")
os.exit()
end)
```
<b>\*</b>A note about multi.NIL, this should only be used within the hold and hold like methods. thread.hold(), thread.holdFor(), and thread.holdWithin() methods. This is not needed within threaded functions! The reason hold prevents nil and false is because it is testing for a condition so the first argument needs to be non nil nor false! multi.NIL should not be used anywhere else. Sometimes you may need to pass a 'nil' value or return. While you could always return true or something you could use multi.NIL to force a nil value through a hold like method. <b>\*</b>A note about multi.NIL, this should only be used within the hold and hold like methods. thread.hold(), thread.holdFor(), and thread.holdWithin() methods. This is not needed within threaded functions! The reason hold prevents nil and false is because it is testing for a condition so the first argument needs to be non nil nor false! multi.NIL should not be used anywhere else. Sometimes you may need to pass a 'nil' value or return. While you could always return true or something you could use multi.NIL to force a nil value through a hold like method.
@@ -474,7 +618,7 @@ Example:
-- Jobs are not natively part of the multi library. I planned on adding them, but decided against it. Below is the code that would have been used. -- Jobs are not natively part of the multi library. I planned on adding them, but decided against it. Below is the code that would have been used.
-- Implementing a job manager using services -- Implementing a job manager using services
package.path="?/init.lua;?.lua;"..package.path package.path="?/init.lua;?.lua;"..package.path
local multi = require("multi") multi,thread = require("multi"):init()
multi.Jobs = multi:newService(function(self,jobs) multi.Jobs = multi:newService(function(self,jobs)
local job = table.remove(jobs,1) local job = table.remove(jobs,1)
if job and job.removed==nil then if job and job.removed==nil then
@@ -532,6 +676,7 @@ jobsn[1]:removeJob() -- Select a job and remove it
multi.Jobs:removeJobs("test2") -- Remove all jobs names 'test2' multi.Jobs:removeJobs("test2") -- Remove all jobs names 'test2'
multi.Jobs.SetScheme(1) -- Jobs are internally a service, so setting scheme and priority multi.Jobs.SetScheme(1) -- Jobs are internally a service, so setting scheme and priority
multi.Jobs.SetPriority(multi.Priority_Core) multi.Jobs.SetPriority(multi.Priority_Core)
multi:mainloop()
``` ```
# CBT: newThread() # CBT: newThread()
@@ -556,21 +701,82 @@ Constants
Examples: Examples:
```lua ```lua
package.path="?/init.lua;?.lua;"..package.path package.path="?/init.lua;?.lua;"..package.path
local multi = require("multi") multi,thread = require("multi"):init()
multi:newThread("Example of basic usage",function() multi:newThread("Example of basic usage",function()
while true do while true do
thread.sleep(1) thread.sleep(1)
print("We just made an alarm!") print("We just made an alarm!")
end end
end) end)
multi:lightloop() multi:mainloop()
``` ```
# CBT: newISOThread()
`th = multi:newThread([STRING name,] FUNCTION func, TABLE: env)` — Creates a new thread with name and function func. Sets the enviroment of the func to env. Both the thread.* and multi.* are automatically placed in the enviroment.
When within a thread, if you have any holding code you will want to use thread.* to give time to other threads while your code is running. This type of thread does not have access to outside local or globals. Only what is in the env can be seen. (This thread was made so pesudo threading could work)
Constants
---
- `th.Name` — Name of thread
- `th.Type` — Type="thread"
- `th.TID` — Thread ID
- `conn = th.OnError(FUNCTION: callback)` — Connect to an event which is triggered when an error is encountered within a thread
- `conn = th.OnDeath(FUNCTION: callback)` — Connect to an event which is triggered when the thread had either been killed or stopped running. (Not triggered when there is an error!)
- `boolean = th:isPaused()`\* — Returns true if a thread has been paused
- `self = th:Pause()`\* — Pauses a thread
- `self = th:Resume()`\* — Resumes a paused thread
- `self = th:Kill()`\* — Kills a thread
- `self = th:Destroy()`\* — Destroys a thread
<b>*</b>Using these methods on a thread directly you are making a request to a thread! The thread may not accept your request, but it most likely will. You can contorl the thread flow within the thread's function itself
```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
multi,thread = require("multi"):init()
GLOBAL,THREAD = require("multi.integration.threading"):init() -- Auto detects your enviroment and uses what's available
jq = multi:newSystemThreadedJobQueue(5) -- Job queue with 4 worker threads
func = jq:newFunction("test",function(a,b)
THREAD.sleep(2)
return a+b
end)
for i = 1,10 do
func(i,i*3).connect(function(data)
print(data)
end)
end
local a = true
b = false
multi:newThread("Standard Thread 1",function()
while true do
thread.sleep(1)
print("Testing 1 ...",a,b,test)
end
end).OnError(function(self,msg)
print(msg)
end)
-- All upvalues are stripped! no access to the global, multi and thread are exposed however
multi:newISOThread("ISO Thread 2",function()
while true do
thread.sleep(1)
print("Testing 2 ...",a,b,test) -- a and b are nil, but test is true
end
end,{test=true,print=print})
.OnError(function(self,msg)
print(msg)
end)
multi:mainloop()
```
# System Threads (ST) - Multi-Integration Getting Started # System Threads (ST) - Multi-Integration Getting Started
The system threads need to be required seperatly. The system threads need to be required seperatly.
```lua ```lua
-- I recommend keeping these as globals. When using lanes you can use local and things will work, but if you use love2d and locals, upvalues are not transfered over threads and this can be an issue -- I recommend keeping these as globals. When using lanes you can use local and things will work, but if you use love2d and locals, upvalues are not transfered over threads and this can be an issue
GLOBAL, THREAD = require("multi.integration.lanesManager"):init() -- We will talk about the global and thread interface that is returned GLOBAL, THREAD = require("multi.integration.threading"):init() -- We will talk about the global and thread interface that is returned
GLOBAL, THREAD = require("multi.integration.loveManager"):init() GLOBAL, THREAD = require("multi.integration.loveManager"):init()
GLOBAL, THREAD = require("luvitManager") --* GLOBAL, THREAD = require("luvitManager") --*
``` ```
@@ -589,7 +795,7 @@ Using this integration modifies some methods that the multi library has.
- `THREAD.kill()` — Kills the thread - `THREAD.kill()` — Kills the thread
- `THREAD.getName()` — Returns the name of the working thread - `THREAD.getName()` — Returns the name of the working thread
- `THREAD.sleep(NUMBER n)` — Sleeps for an amount of time stopping the current thread - `THREAD.sleep(NUMBER n)` — Sleeps for an amount of time stopping the current thread
- `THREAD.hold(FUNCTION func)` — Holds the current thread until a condition is met - `THREAD.hold(FUNCTION func, TABLE options)` — Holds the current thread until a condition is met
- `THREAD.getID()` — returns a unique ID for the current thread. This varaiable is visible to the main thread as well as by accessing it through the returned thread object. OBJ.Id - `THREAD.getID()` — returns a unique ID for the current thread. This varaiable is visible to the main thread as well as by accessing it through the returned thread object. OBJ.Id
# ST - GLOBAL namespace # ST - GLOBAL namespace
@@ -609,8 +815,8 @@ ST - System Threads
System Threads are the feature that allows a user to interact with systen threads. It differs from regular coroutine based thread in how it can interact with variables. When using system threads the GLOBAL table is the "only way"* to send data. Spawning a System thread is really simple once all the required libraries are in place. See example below: System Threads are the feature that allows a user to interact with systen threads. It differs from regular coroutine based thread in how it can interact with variables. When using system threads the GLOBAL table is the "only way"* to send data. Spawning a System thread is really simple once all the required libraries are in place. See example below:
```lua ```lua
local multi = require("multi") -- keep this global when using lanes or implicitly define multi within the spawned thread multi,thread = require("multi"):init() -- keep this global when using lanes or implicitly define multi within the spawned thread
local GLOBAL, THREAD = require("multi.integration.lanesManager").init() local GLOBAL, THREAD = require("multi.integration.threading").init()
multi:newSystemThread("Example thread",function() multi:newSystemThread("Example thread",function()
local multi = require("multi") -- we are in a thread so lets not refer to that upvalue! local multi = require("multi") -- we are in a thread so lets not refer to that upvalue!
print("We have spawned a thread!") print("We have spawned a thread!")
@@ -624,7 +830,7 @@ end,"A message that we are passing") -- There are restrictions on what can be pa
tloop = multi:newTLoop(function() tloop = multi:newTLoop(function()
print("I'm still kicking!") print("I'm still kicking!")
end,1) end,1)
multi:lightloop() multi:mainloop()
``` ```
<b>*</b>This isn't entirely true, as of right now the compatiablity with the lanes library and love2d engine have their own methods to share data, but if you would like to have your code work in both enviroments then using the GLOBAL table and the data structures provided by the multi library will ensure this happens. If you do not plan on having support for both platforms then feel free to use linda's in lanes and channels in love2d. <b>*</b>This isn't entirely true, as of right now the compatiablity with the lanes library and love2d engine have their own methods to share data, but if you would like to have your code work in both enviroments then using the GLOBAL table and the data structures provided by the multi library will ensure this happens. If you do not plan on having support for both platforms then feel free to use linda's in lanes and channels in love2d.
@@ -638,8 +844,8 @@ When creating objects with a name they are automatically exposed to the GLOBAL t
```lua ```lua
-- Exposing a queue -- Exposing a queue
multi = require("multi") multi,thread = require("multi"):init()
local GLOBAL, THREAD = require("multi.integration.lanesManager").init() -- The standard setup above local GLOBAL, THREAD = require("multi.integration.threading").init() -- The standard setup above
queue = multi:newSystemThreadedQueue("myQueue"):init() -- We create and initiate the queue for the main thread queue = multi:newSystemThreadedQueue("myQueue"):init() -- We create and initiate the queue for the main thread
queue:push("This is a test!") -- We push some data onto the queue that other threads can consume and do stuff with queue:push("This is a test!") -- We push some data onto the queue that other threads can consume and do stuff with
multi:newSystemThread("Example thread",function() -- Create a system thread multi:newSystemThread("Example thread",function() -- Create a system thread
@@ -647,7 +853,7 @@ multi:newSystemThread("Example thread",function() -- Create a system thread
local data = queue:pop() -- Get the data local data = queue:pop() -- Get the data
print(data) -- print the data print(data) -- print the data
end) end)
multi:lightloop() multi:mainloop()
``` ```
# ST - SystemThreadedQueue # ST - SystemThreadedQueue
@@ -659,9 +865,9 @@ multi:lightloop()
Let's get into some examples: Let's get into some examples:
```lua ```lua
multi = require("multi") multi,thread = require("multi"):init()
thread_names = {"Thread_A","Thread_B","Thread_C","Thread_D"} thread_names = {"Thread_A","Thread_B","Thread_C","Thread_D"}
local GLOBAL, THREAD = require("multi.integration.lanesManager"):init() local GLOBAL, THREAD = require("multi.integration.threading"):init()
queue = multi:newSystemThreadedQueue("myQueue"):init() queue = multi:newSystemThreadedQueue("myQueue"):init()
for _,n in pairs(thread_names) do for _,n in pairs(thread_names) do
multi:newSystemThread(n,function() multi:newSystemThread(n,function()
@@ -683,13 +889,24 @@ end):OnEvent(function()
print("No more data within the queue!") print("No more data within the queue!")
os.exit() os.exit()
end) end)
multi:lightloop() multi:mainloop()
``` ```
You have probable noticed that the output from this is a total mess! Well I though so too, and created the system threaded console! You have probable noticed that the output from this is a total mess! Well I though so too, and created the system threaded console!
# ST - Using the Console
`console = THREAD.getConsole()`
This does guarantee an order to console output, it does ensure that all things are on nice neat lines
```lua
multi,thread = require("multi"):init()
local GLOBAL, THREAD = require("multi.integration.threading"):init()
console.print("Hello World!")
```
# ST - SystemThreadedJobQueue # ST - SystemThreadedJobQueue
`jq = multi:newSystemThreadedJobQueue([NUMBER: threads])` — Creates a system threaded job queue with an optional number of threads `jq = multi:newSystemThreadedJobQueue([NUMBER: threads])` — Creates a system threaded job queue with an optional number of threads
- `boolean jq:isEmpty()` — Returns true if the jobqueue is empty false otherwise
- `jq.cores = (supplied number) or (the number of cores on your system*2)` - `jq.cores = (supplied number) or (the number of cores on your system*2)`
- `jq.OnJobCompleted(FUNCTION: func(jID,...))` — Connection that is triggered when a job has been completed. The jobID and returns of the job are supplies as arguments - `jq.OnJobCompleted(FUNCTION: func(jID,...))` — Connection that is triggered when a job has been completed. The jobID and returns of the job are supplies as arguments
- `self = jq:doToAll(FUNCTION: func)` — Send data to every thread in the job queue. Useful if you want to require a module and have it available on all threads - `self = jq:doToAll(FUNCTION: func)` — Send data to every thread in the job queue. Useful if you want to require a module and have it available on all threads
@@ -698,13 +915,14 @@ You have probable noticed that the output from this is a total mess! Well I thou
- `handler = jq:newFunction([STRING: name], FUNCTION: func)` — returns a threaded Function that wraps around jq.registerFunction, jq.pushJob() and jq.OnJobCompleted() to provide an easy way to create and work with the jobqueue - `handler = jq:newFunction([STRING: name], FUNCTION: func)` — returns a threaded Function that wraps around jq.registerFunction, jq.pushJob() and jq.OnJobCompleted() to provide an easy way to create and work with the jobqueue
- `handler.connect(Function: func(returns))` — Connects to the event that is triggered when the returns are avaiable - `handler.connect(Function: func(returns))` — Connects to the event that is triggered when the returns are avaiable
- `VARIAABLE returns = handler.wait()` — Waits until returns are avaiable and then returns them - `VARIAABLE returns = handler.wait()` — Waits until returns are avaiable and then returns them
**Note:** Created functions using this method act as normal functions on the queue side of things. So you can call the functions from other queue functions as if they were normal functions. **Note:** Created functions using this method act as normal functions on the queue side of things. So you can call the functions from other queue functions as if they were normal functions.
Example: Example:
```lua ```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
multi = require("multi") multi,thread = require("multi"):init()
GLOBAL, THREAD = require("multi.integration.lanesManager"):init() GLOBAL, THREAD = require("multi.integration.threading"):init()
local jq = multi:newSystemThreadedJobQueue(4) -- job queue using 4 cores local jq = multi:newSystemThreadedJobQueue(4) -- job queue using 4 cores
jq:doToAll(function() jq:doToAll(function()
Important = 15 Important = 15
@@ -727,7 +945,7 @@ func(5,5).connect(function(ret)
print("Connected",ret) print("Connected",ret)
os.exit() os.exit()
end) end)
multi:lightloop() multi:mainloop()
``` ```
# ST - SystemThreadedTable # ST - SystemThreadedTable
`stt = multi:newSystemThreadedTable(STRING: name)` `stt = multi:newSystemThreadedTable(STRING: name)`
@@ -738,15 +956,15 @@ multi:lightloop()
Example: Example:
```lua ```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
multi = require("multi") multi,thread = require("multi"):init()
GLOBAL, THREAD = require("multi.integration.lanesManager"):init() GLOBAL, THREAD = require("multi.integration.threading"):init()
local stt = multi:newSystemThreadedTable("stt") local stt = multi:newSystemThreadedTable("stt")
stt["hello"] = "world" stt["hello"] = "world"
multi:newSystemThread("test thread",function() multi:newSystemThread("test thread",function()
local stt = GLOBAL["stt"]:init() local stt = GLOBAL["stt"]:init()
print(stt["hello"]) print(stt["hello"])
end) end)
multi:lightloop() multi:mainloop()
``` ```
# Network Threads - Multi-Integration WIP Being Reworked # Network Threads - Multi-Integration WIP Being Reworked
More of a fun project of mine then anything core to to the library it will be released and documented when it is ready. I do not have a timeframe for this More of a fun project of mine then anything core to to the library it will be released and documented when it is ready. I do not have a timeframe for this
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2020 Ryan Ward Copyright (c) 2021 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+24 -11
View File
@@ -1,12 +1,16 @@
# Multi Version: 14.2.0 Documentation Complete, Bloat removed! # Multi Version: 15.1.0 Hold the thread
**Key Changes**
- thread.hold has been updated to allow all variants to work as well as some new features. Check the changelog or documentation for more info.
- multi:newProccesor() Creates a process that acts like the multi namespace that can be managed independently from the mainloop.
- Connections can be added together
Found an issue? Please [submit it](https://github.com/rayaman/multi/issues) and I'll look into it! Found an issue? Please [submit it](https://github.com/rayaman/multi/issues) and someone will look into it!
My multitasking library for lua. It is a pure lua binding, with exceptions of the integrations and the love2d compat. If you find any bugs or have any issues, please [let me know](https://github.com/rayaman/multi/issues) and I'll look into it!. My multitasking library for lua. It is a pure lua binding, with exceptions of the integrations and the love2d compat.
INSTALLING INSTALLING
---------- ----------
Links to dependicies: Links to dependencies:
[lanes](https://github.com/LuaLanes/lanes) [lanes](https://github.com/LuaLanes/lanes)
To install copy the multi folder into your environment and you are good to go</br> To install copy the multi folder into your environment and you are good to go</br>
@@ -18,26 +22,35 @@ Going forward I will include a Release zip for love2d.
Discord Discord
------- -------
Have a question that you need asking? Or need realtime assistance? Feel free to join the discord!</br> Have a question? Or need realtime assistance? Feel free to join the discord!</br>
https://discord.gg/U8UspuA</br> https://discord.gg/U8UspuA</br>
Planned features/TODO Planned features/TODO
--------------------- ---------------------
- [x] ~~Finish Documentation~~ Finished - [x] ~~Finish Documentation~~ Finished
- [ ] Create test suite
- [ ] Network Parallelism rework - [ ] Network Parallelism rework
Usage: [Check out the documentation for more info](https://github.com/rayaman/multi/blob/master/Documentation.md)</br> Usage: [Check out the documentation for more info](https://github.com/rayaman/multi/blob/master/Documentation.md)</br>
----- -----
```lua ```lua
local multi, thread = require("multi").init() package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
mutli:newThread("Example",function() local multi, thread = require("multi"):init()
GLOBAL, THREAD = require("multi.integration.threading"):init()
multi:newSystemThread("System Thread",function()
while true do while true do
thread.sleep(1) THREAD.sleep(1)
print("Hello!") print("World!")
end end
end) end)
multi:lightloop() multi:newThread("Coroutine Based Thread",function()
--multi:mainloop() while true do
print("Hello")
thread.sleep(1)
end
end)
multi:mainloop()
--[[ --[[
while true do while true do
multi:uManager() multi:uManager()
+445 -5
View File
@@ -1,8 +1,448 @@
# Changelog # Changelog
Table of contents Table of contents
--- ---
[Update 14.2.0 - Bloatware Removed](#update-1420---bloatware-removed)</br>[Update 14.1.0 - A whole new world of possibilities](#update-1410---a-whole-new-world-of-possibilities)</br>[Update 14.0.0 - Consistency, Additions and Stability](#update-1400---consistency-additions-and-stability)</br>[Update 13.1.0 - Bug fixes and features added](#update-1310---bug-fixes-and-features-added)</br>[Update 13.0.0 - Added some documentation, and some new features too check it out!](#update-1300---added-some-documentation-and-some-new-features-too-check-it-out)</br>[Update 12.2.2 - Time for some more bug fixes!](#update-1222---time-for-some-more-bug-fixes)</br>[Update 12.2.1 - Time for some bug fixes!](#update-1221---time-for-some-bug-fixes)</br>[Update 12.2.0 - The chains of binding](#update-1220---the-chains-of-binding)</br>[Update 12.1.0 - Threads just can't hold on anymore](#update-1210---threads-just-cant-hold-on-anymore)</br>[Update: 12.0.0 - Big update (Lots of additions some changes)](#update-1200---big-update-lots-of-additions-some-changes)</br>[Update: 1.11.1 - Small Clarification on Love](#update-1111---small-clarification-on-love)</br>[Update: 1.11.0](#update-1110)</br>[Update: 1.10.0](#update-1100)</br>[Update: 1.9.2](#update-192)</br>[Update: 1.9.1 - Threads can now argue](#update-191---threads-can-now-argue)</br>[Update: 1.9.0](#update-190)</br>[Update: 1.8.7](#update-187)</br>[Update: 1.8.6](#update-186)</br>[Update: 1.8.5](#update-185)</br>[Update: 1.8.4](#update-184)</br>[Update: 1.8.3 - Mainloop recieves some needed overhauling](#update-183---mainloop-recieves-some-needed-overhauling)</br>[Update: 1.8.2](#update-182)</br>[Update: 1.8.1](#update-181)</br>[Update: 1.7.6](#update-176)</br>[Update: 1.7.5](#update-175)</br>[Update: 1.7.4](#update-174)</br>[Update: 1.7.3](#update-173)</br>[Update: 1.7.2](#update-172)</br>[Update: 1.7.1 - Bug Fixes Only](#update-171---bug-fixes-only)</br>[Update: 1.7.0 - Threading the systems](#update-170---threading-the-systems)</br>[Update: 1.6.0](#update-160)</br>[Update: 1.5.0](#update-150)</br>[Update: 1.4.1 (4/10/2017) - First Public release of the library](#update-141-4102017---first-public-release-of-the-library)</br>[Update: 1.4.0 (3/20/2017)](#update-140-3202017)</br>[Update: 1.3.0 (1/29/2017)](#update-130-1292017)</br>[Update: 1.2.0 (12.31.2016)](#update-120-12312016)</br>[Update: 1.1.0](#update-110)</br>[Update: 1.0.0](#update-100)</br>[Update: 0.6.3](#update-063)</br>[Update: 0.6.2](#update-062)</br>[Update: 0.6.1-6](#update-061-6)</br>[Update: 0.5.1-6](#update-051-6)</br>[Update: 0.4.1](#update-041)</br>[Update: 0.3.0 - The update that started it all](#update-030---the-update-that-started-it-all)</br>[Update: EventManager 2.0.0](#update-eventmanager-200)</br>[Update: EventManager 1.2.0](#update-eventmanager-120)</br>[Update: EventManager 1.1.0](#update-eventmanager-110)</br>[Update: EventManager 1.0.0 - Error checking](#update-eventmanager-100---error-checking)</br>[Version: EventManager 0.0.1 - In The Beginning things were very different](#version-eventmanager-001---in-the-beginning-things-were-very-different) [Update 15.1.0 - Hold the thread!](#update-1510---hold-the-thread)</br>[Update 15.0.0 - The art of faking it](#update-1500---the-art-of-faking-it)</br>[Update 14.2.0 - Bloatware Removed](#update-1420---bloatware-removed)</br>[Update 14.1.0 - A whole new world of possibilities](#update-1410---a-whole-new-world-of-possibilities)</br>[Update 14.0.0 - Consistency, Additions and Stability](#update-1400---consistency-additions-and-stability)</br>[Update 13.1.0 - Bug fixes and features added](#update-1310---bug-fixes-and-features-added)</br>[Update 13.0.0 - Added some documentation, and some new features too check it out!](#update-1300---added-some-documentation-and-some-new-features-too-check-it-out)</br>[Update 12.2.2 - Time for some more bug fixes!](#update-1222---time-for-some-more-bug-fixes)</br>[Update 12.2.1 - Time for some bug fixes!](#update-1221---time-for-some-bug-fixes)</br>[Update 12.2.0 - The chains of binding](#update-1220---the-chains-of-binding)</br>[Update 12.1.0 - Threads just can't hold on anymore](#update-1210---threads-just-cant-hold-on-anymore)</br>[Update: 12.0.0 - Big update (Lots of additions some changes)](#update-1200---big-update-lots-of-additions-some-changes)</br>[Update: 1.11.1 - Small Clarification on Love](#update-1111---small-clarification-on-love)</br>[Update: 1.11.0](#update-1110)</br>[Update: 1.10.0](#update-1100)</br>[Update: 1.9.2](#update-192)</br>[Update: 1.9.1 - Threads can now argue](#update-191---threads-can-now-argue)</br>[Update: 1.9.0](#update-190)</br>[Update: 1.8.7](#update-187)</br>[Update: 1.8.6](#update-186)</br>[Update: 1.8.5](#update-185)</br>[Update: 1.8.4](#update-184)</br>[Update: 1.8.3 - Mainloop recieves some needed overhauling](#update-183---mainloop-recieves-some-needed-overhauling)</br>[Update: 1.8.2](#update-182)</br>[Update: 1.8.1](#update-181)</br>[Update: 1.7.6](#update-176)</br>[Update: 1.7.5](#update-175)</br>[Update: 1.7.4](#update-174)</br>[Update: 1.7.3](#update-173)</br>[Update: 1.7.2](#update-172)</br>[Update: 1.7.1 - Bug Fixes Only](#update-171---bug-fixes-only)</br>[Update: 1.7.0 - Threading the systems](#update-170---threading-the-systems)</br>[Update: 1.6.0](#update-160)</br>[Update: 1.5.0](#update-150)</br>[Update: 1.4.1 (4/10/2017) - First Public release of the library](#update-141-4102017---first-public-release-of-the-library)</br>[Update: 1.4.0 (3/20/2017)](#update-140-3202017)</br>[Update: 1.3.0 (1/29/2017)](#update-130-1292017)</br>[Update: 1.2.0 (12.31.2016)](#update-120-12312016)</br>[Update: 1.1.0](#update-110)</br>[Update: 1.0.0](#update-100)</br>[Update: 0.6.3](#update-063)</br>[Update: 0.6.2](#update-062)</br>[Update: 0.6.1-6](#update-061-6)</br>[Update: 0.5.1-6](#update-051-6)</br>[Update: 0.4.1](#update-041)</br>[Update: 0.3.0 - The update that started it all](#update-030---the-update-that-started-it-all)</br>[Update: EventManager 2.0.0](#update-eventmanager-200)</br>[Update: EventManager 1.2.0](#update-eventmanager-120)</br>[Update: EventManager 1.1.0](#update-eventmanager-110)</br>[Update: EventManager 1.0.0 - Error checking](#update-eventmanager-100---error-checking)</br>[Version: EventManager 0.0.1 - In The Beginning things were very different](#version-eventmanager-001---in-the-beginning-things-were-very-different)
# Update 15.1.0 - Hold the thread!
Full Update Showcase
```lua
package.path = "./?/init.lua;"..package.path
multi,thread = require("multi"):init()
func = thread:newFunction(function(count)
local a = 0
while true do
a = a + 1
thread.sleep(.1)
thread.pushStatus(a,count)
if a == count then break end
end
return "Done"
end)
multi:newThread("Function Status Test",function()
local ret = func(10)
local ret2 = func(15)
local ret3 = func(20)
ret.OnStatus(function(part,whole)
print("Ret1: ",math.ceil((part/whole)*1000)/10 .."%")
end)
ret2.OnStatus(function(part,whole)
print("Ret2: ",math.ceil((part/whole)*1000)/10 .."%")
end)
ret3.OnStatus(function(part,whole)
print("Ret3: ",math.ceil((part/whole)*1000)/10 .."%")
end)
-- Connections can now be added together, if you had multiple holds and one finished before others and wasn't consumed it would lock forever! This is now fixed
thread.hold(ret2.OnReturn + ret.OnReturn + ret3.OnReturn)
print("Function Done!")
os.exit()
end)
test = thread:newFunction(function()
return 1,2,nil,3,4,5,6,7,8,9
end,true)
print(test())
multi:newThread("testing",function()
print("#Test = ",test())
print(thread.hold(function()
print("Hello!")
return false
end,{
interval = 2,
cycles = 3
})) -- End result, 3 attempts within 6 seconds. If still false then timeout
print("held")
end).OnError(function(...)
print(...)
end)
sandbox = multi:newProcessor()
sandbox:newTLoop(function()
print("testing...")
end,1)
test2 = multi:newTLoop(function()
print("testing2...")
end,1)
sandbox:newThread("Test Thread",function()
local a = 0
while true do
thread.sleep(1)
a = a + 1
print("Thread Test: ".. multi.getCurrentProcess().Name)
if a == 10 then
sandbox.Stop()
end
end
end).OnError(function(...)
print(...)
end)
multi:newThread("Test Thread",function()
while true do
thread.sleep(1)
print("Thread Test: ".. multi.getCurrentProcess().Name)
end
end).OnError(function(...)
print(...)
end)
sandbox.Start()
multi:mainloop()
```
Added:
---
## multi:newSystemThreadedJobQueue(n) isEmpty()
- returns true if the queue is empty, false if there are items in the queue.
**Note:** a queue might be empty, but the job may still be running and not finished yet! Also if a registered function is called directly instead of pushed, it will not reflect inside the queue until the next cycle!
Example:
```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
package.cpath = [[C:\Program Files (x86)\Lua\5.1\systree\lib\lua\5.1\?.dll;C:\Program Files (x86)\Lua\5.1\systree\lib\lua\5.1\?\core.dll;]] ..package.cpath
multi,thread = require("multi"):init()
GLOBAL,THREAD = require("multi.integration.threading"):init() -- Auto detects your enviroment and uses what's available
jq = multi:newSystemThreadedJobQueue(5) -- Job queue with 4 worker threads
func = jq:newFunction("test",function(a,b)
THREAD.sleep(2)
return a+b
end)
for i = 1,10 do
func(i,i*3).connect(function(data)
print(data)
end)
end
local a = true
b = false
multi:newThread("Standard Thread 1",function()
while true do
thread.sleep(.1)
print("Empty:",jq:isEmpty())
end
end).OnError(function(self,msg)
print(msg)
end)
multi:mainloop()
```
## multi.TIMEOUT
`multi.TIMEOUT` is equal to "TIMEOUT", it is reccomended to use this incase things change later on. There are plans to change the timeout value to become a custom object instead of a string.
## new connections on threaded functions
- `func.OnStatus(...)`
Allows you to connect to the status of a function see [thread.pushStatus()](#status-added-to-threaded-functions)
- `func.OnReturn(...)`
Allows you to connect to the functions return event and capture its returns see [Example](#status-added-to-threaded-functions) for an example of it in use.
## multi:newProcessor(name)
```lua
package.path = "./?/init.lua;"..package.path
multi,thread = require("multi"):init()
-- Create a processor object, it works a lot like the multi object
sandbox = multi:newProcessor()
-- On our processor object create a TLoop that prints "testing..." every second
sandbox:newTLoop(function()
print("testing...")
end,1)
-- Create a thread on the processor object
sandbox:newThread("Test Thread",function()
-- Create a counter named 'a'
local a = 0
-- Start of the while loop that ends when a = 10
while true do
-- pause execution of the thread for 1 second
thread.sleep(1)
-- increment a by 1
a = a + 1
-- display the name of the current process
print("Thread Test: ".. multi.getCurrentProcess().Name)
if a == 10 then
-- Stopping the processor stops all objects created inside that process including threads. In the backend threads use a regular multiobject to handle the scheduler and all of the holding functions. These all stop when a processor is stopped. This can be really useful to sandbox processes that might need to turned on and off with ease and not having to think about it.
sandbox.Stop()
end
end
-- Catch any errors that may come up
end).OnError(function(...)
print(...)
end)
sandbox.Start() -- Start the process
multi:mainloop() -- The main loop that allows all processes to continue
```
**Note:** Processor objects have been added and removed many times in the past, but will remain with this update.
| Attribute | Type | Returns | Description |
---|---|---|---
Start|Method()|self| Starts the process
Stop|Method()|self| Stops the process
OnError|Connection|connection| Allows connection to the process error handler
Type|Member:`string`|"process"| Contains the type of object
Active|Member:`boolean`|variable| If false the process is not active
Name|Member:`string`|variable| The name set at process creation
process|Thread|thread| A handle to a multi thread object
**Note:** All tasks/threads created on a process are linked to that process. If a process is stopped all tasks/threads will be halted until the process is started back up.
## Connection can now be added together
Very useful when using thread.hold for multiple connections to trigger.
Iif you had multiple holds and one finished before others and wasn't consumed it would lock forever! This is now fixed
`print(conn + conn2 + conn3 + connN)`
Can be chained as long as you want! See example below
## Status added to threaded functions
- `thread.pushStatus(...)`
Allows a developer to push a status from a function.
- `tFunc.OnStatus(func(...))`
A connection that can be used on a function to view the status of the threaded function
Example:
```lua
package.path = "./?/init.lua;"..package.path
multi,thread = require("multi"):init()
func = thread:newFunction(function(count)
local a = 0
while true do
a = a + 1
thread.sleep(.1)
thread.pushStatus(a,count)
if a == count then break end
end
return "Done"
end)
multi:newThread("Function Status Test",function()
local ret = func(10)
local ret2 = func(15)
local ret3 = func(20)
ret.OnStatus(function(part,whole)
--[[ Print out the current status. In this case every second it will update with:
10%
20%
30%
...
100%
Function Done!
]]
print(math.ceil((part/whole)*1000)/10 .."%")
end)
ret2.OnStatus(function(part,whole)
print("Ret2: ",math.ceil((part/whole)*1000)/10 .."%")
end)
ret3.OnStatus(function(part,whole)
print("Ret3: ",math.ceil((part/whole)*1000)/10 .."%")
end)
-- Connections can now be added together, if you had multiple holds and one finished before others and wasn't consumed it would lock forever! This is now fixed
thread.hold(ret2.OnReturn + ret.OnReturn + ret3.OnReturn)
print("Function Done!")
os.exit()
end)
```
Changed:
---
- `f = thread:newFunction(func,holdme)`
- Nothing changed that will affect how the object functions by default. The returned function is now a table that is callable and 3 new methods have been added:
Method | Description
---|---
Pause() | Pauses the function, Will cause the function to return `nil, Function is paused`
Resume() | Resumes the function
holdMe(set) | Sets the holdme argument that existed at function creation
```lua
package.path = "./?/init.lua;"..package.path
multi, thread = require("multi"):init()
test = thread:newFunction(function(a,b)
thread.sleep(1)
return a,b
end, true)
print(test(1,2))
test:Pause()
print(test(1,2))
test:Resume()
print(test(1,2))
--[[ -- If you left holdme nil/false
print(test(1,2).connect(function(...)
print(...)
end))
test:Pause()
print(test(1,2).connect(function(...)
print(...)
end))
test:Resume()
print(test(1,2).connect(function(...)
print(...)
end))
]]
multi:mainloop()
```
**Output:**
```
1 2
nil Function is paused
1 2
```
**If holdme is nil/false:**
```
nil Function is paused
1 2 nil...
1 2 nil...
```
- thread.hold(n,opt) [Ref. Issue](https://github.com/rayaman/multi/issues/24)
- Added option table to thread.hold
| Option | Description |
---|---
| interval | Time between each poll |
| cycles | Number of cycles before timing out |
| sleep | Number of seconds before timing out |
| skip | Number of cycles before testing again, does not cause a timeout! |
**Note:** cycles and sleep options cannot both be used at the same time. Interval and skip cannot be used at the same time either. Cycles take priority over sleep if both are present! HoldFor and HoldWithin can be emulated using the new features. Old functions will remain for backward compatibility.
Using cycles, sleep or interval will cause a timeout; returning nil, multi.TIMEOUT
- `n` can be a number and thread.hold will act like thread.sleep. When `n` is a number the option table will be ignored!
Removed:
---
- N/A
Fixed:
---
- Threaded functions not returning multiple values [Ref. Issue](https://github.com/rayaman/multi/issues/21)
- Priority Lists not containing Very_High and Very_Low from previous update
- All functions that should have chaining now do, reminder all functions that don't return any data return a reference to itself to allow chaining of method calls.
ToDo
---
- Work on network parallelism (I really want to make this, but time and getting it right is proving much more difficult)
- Work on QOL changes to allow cleaner code like [this](#connection-can-now-be-added-together)
# Update 15.0.0 - The art of faking it
Full Update Showcase
---
```lua
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path
multi,thread = require("multi"):init()
GLOBAL,THREAD = require("multi.integration.threading"):init() -- Auto detects your enviroment and uses what's available
jq = multi:newSystemThreadedJobQueue(4) -- Job queue with 4 worker threads
func = jq:newFunction("test",function(a,b)
THREAD.sleep(2)
return a+b
end)
for i = 1,10 do
func(i,i*3).connect(function(data)
print(data)
end)
end
multi:newThread("Standard Thread 1",function()
while true do
thread.sleep(1)
print("Testing 1 ...")
end
end)
multi:newISOThread("ISO Thread 2",{test=true},function()
while true do
thread.sleep(1)
print("Testing 2 ...")
end
end)
multi:mainloop()
```
Note:
---
This was supposed to be released over a year ago, but work and other things got in my way. Pesudo Threading now works. The goal of this is so you can write modules that can be scaled up to utilize threading features when available.
Added:
---
- multi:newISOThread(name,func,env)
- Creates an isolated thread that prevents both locals and globals from being accessed.
- Was designed for the pesudoManager so it can emulate threads. You can use it as a super sandbox, but remember upvalues are also stripped which was intened for what I wanted them to do!
- Added new integration: pesudoManager, functions just like lanesManager and loveManager, but it's actually single threaded
- This was implemented because, you may want to build your code around being multi threaded, but some systems/implemetations of lua may not permit this. Since we now have a "single threaded" implementation of multi threading. We can actually create scalable code where things automatcally are threaded if built correctly. I am planning on adding more threadedOjbects.
- In addition to adding pesudo Threading `multi.integration.threading` can now be used to autodetect which enviroment you are on and use the threading features.
```
GLOBAL,THREAD = require("multi.integration.threading"):init()
```
If you are using love2d it will use that, if you have lanes avaialble then it will use lanes. Otherwise it will use pesudo threading. This allows module creators to implement scalable features without having to worry about which enviroment they are in. Can now require a consistant module: `require("multi.integration.threading"):init()`
Changed:
---
- Documentation to reflect the changes made
Removed:
---
- CBT (Coroutine Based threading) has lost a feature, one that hasn't been used much, but broke compatiblity with anything above lua 5.1. My goal is to make my library work with all versions of lua above 5.1, including 5.4. Lua 5.2+ changed how enviroments worked which means that you can no longer modify an enviroment of function without using the debug library. This isn't ideal for how things in my library worked, but it is what it is. The feature lost is the one that converted all functions within a threaded enviroment into a threadedfunction. This in hindsight wasn't the best pratice and if it is the desired state you as the user can manually do that anyway. This shouldn't affect anyones code in a massive way.
Fixed:
---
- pseudoThreading and threads had an issue where they weren't executing properly
- lanesManager THREAD:get(STRING: name) not returning the value
- Issue where threaded function were not returning multiple values
Todo:
---
- Add more details to the documentation
# Update 14.2.0 - Bloatware Removed # Update 14.2.0 - Bloatware Removed
Full Update Showcase Full Update Showcase
@@ -64,7 +504,7 @@ Quality Of Life:
Added: Added:
--- ---
- Type: destroyed - Type: destroyed
- A special state of an object that causes that object to become immutable and callable. The object Type is always "destroyed" it cannot be changed. The object can be indexed to infinity without issue. Every part of the object can be called as if it were a function including the indexed parts. This is done incase you destroy an object and still use it somewhere. However, if you are expecting something from the object then you may still encounter an error, though the returned type is an instance of the destroyed object which can be indexed and called like normal. This object can be used in any way and no errors will come about with it. - A special state of an object that causes that object to become immutable and callable. The object Type is always "destroyed" it cannot be changed. The object can be indexed to infinity without issue. Every part of the object can be called as if it were a function including the indexed parts. This is done incase you destroy an object and still "use" it somewhere. However, if you are expecting something from the object then you may still encounter an error, though the returned type is an instance of the destroyed object which can be indexed and called like normal. This object can be used in any way and no errors will come about with it.
Fixed: Fixed:
--- ---
@@ -299,7 +739,7 @@ Changed:
- thread:newFunction(func,holup) — Added an argument holup to always force the threaded funcion to wait. Meaning you don't need to tell it to func().wait() or func().connect() - thread:newFunction(func,holup) — Added an argument holup to always force the threaded funcion to wait. Meaning you don't need to tell it to func().wait() or func().connect()
- multi:newConnection(protect,callback,kill) — Added the kill argument. Makes connections work sort of like a stack. Pop off the connections as they get called. So a one time connection handler. - multi:newConnection(protect,callback,kill) — Added the kill argument. Makes connections work sort of like a stack. Pop off the connections as they get called. So a one time connection handler.
- I'm not sure callback has been documented in any form. callback gets called each and everytime conn:Fire() gets called! As well as being triggered for each connfunc that is part of the connection. - I'm not sure callback has been documented in any form. callback gets called each and everytime conn:Fire() gets called! As well as being triggered for each connfunc that is part of the connection.
- modified the lanes manager to create globals GLOBAL and THREAD when a thread is started. This way you are now able to more closely mirror code between lanes and love. As of right now parity between both enviroments is now really good. Upvalues being copied by default in lanes is something that I will not try and mirror in love. It's better to pass what you need as arguments, this way you can keep things consistant. looping thorugh upvalues and sterlizing them and sending them are very complex and slow opperations. - modified the lanes manager to create globals GLOBAL and THREAD when a thread is started. This way you are now able to more closely mirror code between lanes and love. As of right now parity between both enviroments is now really good. Upvalues being copied by default in lanes is something that I will not try and mirror in love. It's better to pass what you need as arguments, this way you can keep things consistant. looping through upvalues and sterlizing them and sending them are very complex and slow.
Removed: Removed:
--- ---
@@ -547,7 +987,7 @@ Tasks Details Table format
# Update 13.0.0 - Added some documentation, and some new features too check it out! # Update 13.0.0 - Added some documentation, and some new features too check it out!
------------- -------------
**Quick note** on the 13.0.0 update: **Quick note** on the 13.0.0 update:
This update I went all in finding bugs and improving proformance within the library. I added some new features and the new task manager, which I used as a way to debug the library was a great help, so much so thats it is now a permanent feature. It's been about half a year since my last update, but so much work needed to be done. I hope you can find a use in your code to use my library. I am extremely proud of my work; 7 years of development, I learned so much about lua and programming through the creation of this library. It was fun, but there will always be more to add and bugs crawling there way in. I can't wait to see where this library goes in the future! This update I went all in finding bugs and improving performance within the library. I added some new features and the new task manager, which I used as a way to debug the library was a great help, so much so thats it is now a permanent feature. It's been about half a year since my last update, but so much work needed to be done. I hope you can find a use in your code to use my library. I am extremely proud of my work; 7 years of development, I learned so much about lua and programming through the creation of this library. It was fun, but there will always be more to add and bugs crawling there way in. I can't wait to see where this library goes in the future!
Fixed: Fixed:
--- ---
+178
View File
@@ -21,6 +21,184 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
]] ]]
if table.unpack then
unpack=table.unpack
end
function table.val_to_str ( v )
if "string" == type( v ) then
v = string.gsub( v, "\n", "\\n" )
if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
return "'" .. v .. "'"
end
return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
else
return "table" == type( v ) and table.tostring( v ) or
tostring( v )
end
end
function table.key_to_str ( k )
if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
return k
else
return "[" .. table.val_to_str( k ) .. "]"
end
end
function table.tostring( tbl )
local result, done = {}, {}
for k, v in ipairs( tbl ) do
table.insert( result, table.val_to_str( v ) )
done[ k ] = true
end
for k, v in pairs( tbl ) do
if not done[ k ] then
table.insert( result,
table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
end
end
return "{" .. table.concat( result, "," ) .. "}"
end
function table.merge(t1, t2)
t1,t2= t1 or {},t2 or {}
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
table.merge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
Library={}
function Library.inject(lib,dat,arg)
if type(lib)=="table" then
if type(dat)=="table" then
table.merge(lib,dat)
elseif type(dat)=="string" then
if lib.Version and dat:match("(%d-)%.(%d-)%.(%d-)") then
lib.Version={dat:match("(%d+)%.(%d+)%.(%d+)")}
elseif dat=="meta" and type(arg)=="table" then
local _mt=getmetatable(lib) or {}
local mt={}
table.merge(mt,arg)
table.merge(_mt,mt)
setmetatable(lib,_mt)
elseif dat=="compat" then
lib["getVersion"]=function(self) return self.Version[1].."."..self.Version[2].."."..self.Version[3] end
if not lib.Version then
lib.Version={1,0,0}
end
elseif dat=="inhert" then
if not(lib["!%"..arg.."%!"]) then print("Wrong Password!!") return end
lib["!%"..arg.."%!"].__index=lib["!!%"..arg.."%!!"]
end
elseif type(dat)=="function" then
for i,v in pairs(lib) do
dat(lib,i,v)
end
end
elseif type(lib)=="function" or type(lib)=="userdata" then
if lib==unpack then
print("function unpack cannot yet be injected!")
return unpack
elseif lib==pairs then
print("function pairs cannot yet be injected!")
return lib
elseif lib==ipairs then
print("function ipairs cannot yet be injected!")
return lib
elseif lib==type then
print("function type cannot yet be injected!")
return lib
end
temp={}
local mt={
__call=function(t,...)
local consume,MainRet,init={},{},{...}
local tt={}
for i=1,#t.__Link do
tt={}
if t.__Link[i]==t.__Main then
if #consume~=0 then
MainRet={t.__Link[i](unpack(consume))}
else
MainRet={t.__Link[i](unpack(init))}
end
else
if i==1 then
consume=(t.__Link[i](unpack(init)))
else
if type(MainRet)=="table" then
table.merge(tt,MainRet)
end
if type(consume)=="table" then
table.merge(tt,consume)
end
consume={t.__Link[i](unpack(tt))}
end
if i==#t.__Link then
return unpack(consume)
end
if consume then if consume[0]=="\1\7\6\3\2\99\125" then consume[0]=nil return unpack(consume) end end
end
end
if type(MainRet)=="table" then
table.merge(tt,MainRet)
end
if type(consume)=="table" then
table.merge(tt,consume)
end
return unpack(tt)
end,
}
temp.__Link={lib}
temp.__Main=lib
temp.__self=temp
function temp:inject(func,i)
if i then
table.insert(self.__Link,i,func)
else
table.insert(self.__Link,func)
end
end
function temp:consume(func)
for i=1,#self.__Link do
if self.__Link[i]==self.__Main then
self.__Link[i]=func
self.__self.__Main=func
return true
end
end
return false
end
setmetatable(temp,mt)
return temp
else
return "arg1 must be a table or a function"
end
end
function Library.convert(...)
local temp,rets={...},{}
for i=1,#temp do
if type(temp[i])=="function" then
table.insert(rets,Library.inject(temp[i]))
else
error("Takes only functions and returns in order from functions given. arg # "..i.." is not a function!!! It is a "..type(temp[i]))
end
end
return unpack(rets)
end
local link={MainLibrary=Library}
Library.inject(Library,"meta",{
__Link=link,
__call=function(self,func) func(link) end,
})
local multi, thread = require("multi").init() local multi, thread = require("multi").init()
os.sleep = love.timer.sleep os.sleep = love.timer.sleep
multi.drawF = {} multi.drawF = {}
+281
View File
@@ -0,0 +1,281 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
if table.unpack then
unpack=table.unpack
end
function table.val_to_str ( v )
if "string" == type( v ) then
v = string.gsub( v, "\n", "\\n" )
if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
return "'" .. v .. "'"
end
return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
else
return "table" == type( v ) and table.tostring( v ) or
tostring( v )
end
end
function table.key_to_str ( k )
if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
return k
else
return "[" .. table.val_to_str( k ) .. "]"
end
end
function table.tostring( tbl )
local result, done = {}, {}
for k, v in ipairs( tbl ) do
table.insert( result, table.val_to_str( v ) )
done[ k ] = true
end
for k, v in pairs( tbl ) do
if not done[ k ] then
table.insert( result,
table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
end
end
return "{" .. table.concat( result, "," ) .. "}"
end
function table.merge(t1, t2)
t1,t2= t1 or {},t2 or {}
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
table.merge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
Library={}
function Library.inject(lib,dat,arg)
if type(lib)=="table" then
if type(dat)=="table" then
table.merge(lib,dat)
elseif type(dat)=="string" then
if lib.Version and dat:match("(%d-)%.(%d-)%.(%d-)") then
lib.Version={dat:match("(%d+)%.(%d+)%.(%d+)")}
elseif dat=="meta" and type(arg)=="table" then
local _mt=getmetatable(lib) or {}
local mt={}
table.merge(mt,arg)
table.merge(_mt,mt)
setmetatable(lib,_mt)
elseif dat=="compat" then
lib["getVersion"]=function(self) return self.Version[1].."."..self.Version[2].."."..self.Version[3] end
if not lib.Version then
lib.Version={1,0,0}
end
elseif dat=="inhert" then
if not(lib["!%"..arg.."%!"]) then print("Wrong Password!!") return end
lib["!%"..arg.."%!"].__index=lib["!!%"..arg.."%!!"]
end
elseif type(dat)=="function" then
for i,v in pairs(lib) do
dat(lib,i,v)
end
end
elseif type(lib)=="function" or type(lib)=="userdata" then
if lib==unpack then
print("function unpack cannot yet be injected!")
return unpack
elseif lib==pairs then
print("function pairs cannot yet be injected!")
return lib
elseif lib==ipairs then
print("function ipairs cannot yet be injected!")
return lib
elseif lib==type then
print("function type cannot yet be injected!")
return lib
end
temp={}
local mt={
__call=function(t,...)
local consume,MainRet,init={},{},{...}
local tt={}
for i=1,#t.__Link do
tt={}
if t.__Link[i]==t.__Main then
if #consume~=0 then
MainRet={t.__Link[i](unpack(consume))}
else
MainRet={t.__Link[i](unpack(init))}
end
else
if i==1 then
consume=(t.__Link[i](unpack(init)))
else
if type(MainRet)=="table" then
table.merge(tt,MainRet)
end
if type(consume)=="table" then
table.merge(tt,consume)
end
consume={t.__Link[i](unpack(tt))}
end
if i==#t.__Link then
return unpack(consume)
end
if consume then if consume[0]=="\1\7\6\3\2\99\125" then consume[0]=nil return unpack(consume) end end
end
end
if type(MainRet)=="table" then
table.merge(tt,MainRet)
end
if type(consume)=="table" then
table.merge(tt,consume)
end
return unpack(tt)
end,
}
temp.__Link={lib}
temp.__Main=lib
temp.__self=temp
function temp:inject(func,i)
if i then
table.insert(self.__Link,i,func)
else
table.insert(self.__Link,func)
end
end
function temp:consume(func)
for i=1,#self.__Link do
if self.__Link[i]==self.__Main then
self.__Link[i]=func
self.__self.__Main=func
return true
end
end
return false
end
setmetatable(temp,mt)
return temp
else
return "arg1 must be a table or a function"
end
end
function Library.convert(...)
local temp,rets={...},{}
for i=1,#temp do
if type(temp[i])=="function" then
table.insert(rets,Library.inject(temp[i]))
else
error("Takes only functions and returns in order from functions given. arg # "..i.." is not a function!!! It is a "..type(temp[i]))
end
end
return unpack(rets)
end
local link={MainLibrary=Library}
Library.inject(Library,"meta",{
__Link=link,
__call=function(self,func) func(link) end,
})
local multi, thread = require("multi").init()
os.sleep = lovr.timer.sleep
multi.drawF = {}
function multi:onDraw(func, i)
i = i or 1
table.insert(self.drawF, i, func)
end
multi.OnKeyPressed = multi:newConnection()
multi.OnKeyReleased = multi:newConnection()
multi.OnErrHand = multi:newConnection()
multi.OnFocus = multi:newConnection()
multi.OnLoad = multi:newConnection()
multi.OnLog = multi:newConnection()
multi.OnPermission = multi:newConnection()
multi.OnResize = multi:newConnection()
multi.OnRestart = multi:newConnection()
multi.OnThreadError = multi:newConnection()
multi.OnDraw = multi:newConnection()
multi.OnTextInput = multi:newConnection()
multi.OnUpdate = multi:newConnection()
multi.OnQuit = multi:newConnection()
multi.OnPreLoad(function()
local function Hook(func, conn)
if lovr[func] ~= nil then
lovr[func] = Library.convert(lovr[func])
lovr[func]:inject(function(...)
conn:Fire(...)
return {...}
end,1)
elseif lovr[func] == nil then
lovr[func] = function(...)
conn:Fire(...)
end
end
end
Hook("quit", multi.OnQuit)
Hook("keypressed", multi.OnKeyPressed)
Hook("keyreleased", multi.OnKeyReleased)
Hook("focus", multi.OnFocus)
Hook("log", multi.OnLog)
Hook("errhand", multi.OnErrHand)
Hook("load", multi.OnLoad)
Hook("draw", multi.OnDraw)
Hook("textinput", multi.OnTextInput)
Hook("update", multi.OnUpdate)
Hook("permission", multi.OnPermission)
Hook("resize", multi.OnResize)
Hook("restart", multi.OnRestart)
Hook("threaderror", multi.OnThreadError)
multi.OnDraw(function()
for i = 1, #multi.drawF do
lovr.graphics.setColor(255, 255, 255, 255)
multi.drawF[i]()
end
end)
end)
function multi:lovrloop(light)
local link
link = multi:newThread(function()
local mainloop = lovr.run()
while true do
thread.yield()
pcall(mainloop)
end
end).OnError(function(...)
print(...)
end)
if light==false then
multi:mainloop()
else
multi:lightloop()
end
end
multi.OnQuit(function()
multi.Stop()
lovr.event.quit()
end)
return multi
+346 -97
View File
File diff suppressed because it is too large Load Diff
@@ -68,6 +68,9 @@ function multi:newSystemThreadedJobQueue(n)
local doAll = multi:newSystemThreadedQueue() local doAll = multi:newSystemThreadedQueue()
local ID=1 local ID=1
local jid = 1 local jid = 1
function c:isEmpty()
return queueJob:peek()==nil
end
function c:doToAll(func) function c:doToAll(func)
for i=1,c.cores do for i=1,c.cores do
doAll:push{ID,func} doAll:push{ID,func}
@@ -100,7 +103,7 @@ function multi:newSystemThreadedJobQueue(n)
link = c.OnJobCompleted(function(jid,...) link = c.OnJobCompleted(function(jid,...)
if id==jid then if id==jid then
rets = {...} rets = {...}
link:Remove() link:Destroy()
end end
end) end)
return thread.hold(function() return thread.hold(function()
+2 -2
View File
@@ -23,7 +23,7 @@ SOFTWARE.
]] ]]
package.path = "?/init.lua;?.lua;" .. package.path package.path = "?/init.lua;?.lua;" .. package.path
multi, thread = require("multi").init() -- get it all and have it on all lanes multi, thread = require("multi").init() -- get it all and have it on all lanes
if multi.integration then -- This allows us to call the lanes manager from supporting modules without a hassel if multi.integration then -- This allows us to call the lanes manager from supporting modules without a hassle
return { return {
init = function() init = function()
return multi.integration.GLOBAL, multi.integration.THREAD return multi.integration.GLOBAL, multi.integration.THREAD
@@ -145,7 +145,7 @@ function multi.InitSystemThreadErrorHandler()
end end
) )
end end
multi.print("Integrated Lanes!") print("Integrated Lanes!")
multi.integration = {} -- for module creators multi.integration = {} -- for module creators
multi.integration.GLOBAL = GLOBAL multi.integration.GLOBAL = GLOBAL
multi.integration.THREAD = THREAD multi.integration.THREAD = THREAD
+1 -1
View File
@@ -41,7 +41,7 @@ local function INIT(__GlobalLinda,__SleepingLinda)
__GlobalLinda:set(name, val) __GlobalLinda:set(name, val)
end end
function THREAD.get(name) function THREAD.get(name)
__GlobalLinda:get(name) return __GlobalLinda:get(name)
end end
function THREAD.waitFor(name) function THREAD.waitFor(name)
local function wait() local function wait()
+6 -1
View File
@@ -21,6 +21,8 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
]] ]]
-- TODO make compatible with lovr
local multi, thread = require("multi").init() local multi, thread = require("multi").init()
GLOBAL = multi.integration.GLOBAL GLOBAL = multi.integration.GLOBAL
THREAD = multi.integration.THREAD THREAD = multi.integration.THREAD
@@ -99,6 +101,9 @@ function multi:newSystemThreadedJobQueue(n)
self.id = self.id + 1 self.id = self.id + 1
self.queue:push{name,self.id,...} self.queue:push{name,self.id,...}
return self.id return self.id
end
function c:isEmpty()
return queueJob:peek()==nil
end end
local nFunc = 0 local nFunc = 0
function c:newFunction(name,func,holup) -- This registers with the queue function c:newFunction(name,func,holup) -- This registers with the queue
@@ -116,7 +121,7 @@ function multi:newSystemThreadedJobQueue(n)
link = c.OnJobCompleted(function(jid,...) link = c.OnJobCompleted(function(jid,...)
if id==jid then if id==jid then
rets = {...} rets = {...}
link:Remove() link:Destroy()
end end
end) end)
return thread.hold(function() return thread.hold(function()
+1
View File
@@ -81,6 +81,7 @@ end
multi.integration.GLOBAL = GLOBAL multi.integration.GLOBAL = GLOBAL
multi.integration.THREAD = THREAD multi.integration.THREAD = THREAD
require("multi.integration.loveManager.extensions") require("multi.integration.loveManager.extensions")
print("Integrated Love Threading!")
return {init=function() return {init=function()
return GLOBAL,THREAD return GLOBAL,THREAD
end} end}
@@ -0,0 +1,203 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
local multi, thread = require("multi").init()
GLOBAL = multi.integration.GLOBAL
THREAD = multi.integration.THREAD
function multi:newSystemThreadedQueue(name)
local c = {}
c.Name = name
local fRef = {"func",nil}
function c:init()
local q = {}
q.chan = lovr.thread.getChannel(self.Name)
function q:push(dat)
if type(dat) == "function" then
fRef[2] = THREAD.dump(dat)
self.chan:push(fRef)
return
else
self.chan:push(dat)
end
end
function q:pop()
local dat = self.chan:pop()
if type(dat)=="table" and dat[1]=="func" then
return THREAD.loadDump(dat[2])
else
return dat
end
end
function q:peek()
local dat = self.chan:peek()
if type(dat)=="table" and dat[1]=="func" then
return THREAD.loadDump(dat[2])
else
return dat
end
end
return q
end
THREAD.package(name,c)
return c
end
function multi:newSystemThreadedTable(name)
local c = {}
c.name = name
function c:init()
return THREAD.createTable(self.name)
end
THREAD.package(name,c)
return c
end
local jqc = 1
function multi:newSystemThreadedJobQueue(n)
local c = {}
c.cores = n or THREAD.getCores()
c.registerQueue = {}
c.funcs = THREAD.createStaticTable("__JobQueue_"..jqc.."_table")
c.queue = lovr.thread.getChannel("__JobQueue_"..jqc.."_queue")
c.queueReturn = lovr.thread.getChannel("__JobQueue_"..jqc.."_queueReturn")
c.queueAll = lovr.thread.getChannel("__JobQueue_"..jqc.."_queueAll")
c.id = 0
c.OnJobCompleted = multi:newConnection()
local allfunc = 0
function c:doToAll(func)
local f = THREAD.dump(func)
for i = 1, self.cores do
self.queueAll:push({allfunc,f})
end
allfunc = allfunc + 1
end
function c:registerFunction(name,func)
if self.funcs[name] then
error("A function by the name "..name.." has already been registered!")
end
self.funcs[name] = func
end
function c:pushJob(name,...)
self.id = self.id + 1
self.queue:push{name,self.id,...}
return self.id
end
function c:isEmpty()
return queueJob:peek()==nil
end
local nFunc = 0
function c:newFunction(name,func,holup) -- This registers with the queue
if type(name)=="function" then
holup = func
func = name
name = "JQ_Function_"..nFunc
end
nFunc = nFunc + 1
c:registerFunction(name,func)
return thread:newFunction(function(...)
local id = c:pushJob(name,...)
local link
local rets
link = c.OnJobCompleted(function(jid,...)
if id==jid then
rets = {...}
link:Destroy()
end
end)
return thread.hold(function()
if rets then
return unpack(rets) or multi.NIL
end
end)
end,holup),name
end
multi:newThread("jobManager",function()
while true do
thread.yield()
local dat = c.queueReturn:pop()
if dat then
c.OnJobCompleted:Fire(unpack(dat))
end
end
end)
for i=1,c.cores do
multi:newSystemThread("JobQueue_"..jqc.."_worker_"..i,function(jqc)
local multi, thread = require("multi"):init()
require("lovr.timer")
local function atomic(channel)
return channel:pop()
end
local clock = os.clock
local funcs = THREAD.createStaticTable("__JobQueue_"..jqc.."_table")
local queue = lovr.thread.getChannel("__JobQueue_"..jqc.."_queue")
local queueReturn = lovr.thread.getChannel("__JobQueue_"..jqc.."_queueReturn")
local lastProc = clock()
local queueAll = lovr.thread.getChannel("__JobQueue_"..jqc.."_queueAll")
local registry = {}
setmetatable(_G,{__index = funcs})
multi:newThread("startUp",function()
while true do
thread.yield()
local all = queueAll:peek()
if all and not registry[all[1]] then
lastProc = os.clock()
THREAD.loadDump(queueAll:pop()[2])()
end
end
end)
multi:newThread("runner",function()
thread.sleep(.1)
while true do
thread.yield()
local all = queueAll:peek()
if all and not registry[all[1]] then
lastProc = os.clock()
THREAD.loadDump(queueAll:pop()[2])()
end
local dat = queue:performAtomic(atomic)
if dat then
lastProc = os.clock()
local name = table.remove(dat,1)
local id = table.remove(dat,1)
local tab = {funcs[name](unpack(dat))}
table.insert(tab,1,id)
queueReturn:push(tab)
end
end
end):OnError(function(...)
error(...)
end)
multi:newThread("Idler",function()
while true do
thread.yield()
if clock()-lastProc> 2 then
THREAD.sleep(.05)
else
THREAD.sleep(.001)
end
end
end)
multi:mainloop()
end,jqc)
end
jqc = jqc + 1
return c
end
+88
View File
@@ -0,0 +1,88 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
-- TODO make compatible with lovr
if ISTHREAD then
error("You cannot require the lovrManager from within a thread!")
end
local ThreadFileData = [[
ISTHREAD = true
THREAD = require("multi.integration.lovrManager.threads") -- order is important!
sThread = THREAD
__IMPORTS = {...}
__FUNC__=table.remove(__IMPORTS,1)
__THREADID__=table.remove(__IMPORTS,1)
__THREADNAME__=table.remove(__IMPORTS,1)
stab = THREAD.createStaticTable(__THREADNAME__)
GLOBAL = THREAD.getGlobal()
multi, thread = require("multi").init()
stab["returns"] = {THREAD.loadDump(__FUNC__)(unpack(__IMPORTS))}
]]
local multi, thread = require("multi.compat.lovr2d"):init()
local THREAD = {}
__THREADID__ = 0
__THREADNAME__ = "MainThread"
multi.integration={}
multi.integration.lovr2d={}
local THREAD = require("multi.integration.lovrManager.threads")
local GLOBAL = THREAD.getGlobal()
local THREAD_ID = 1
local OBJECT_ID = 0
local stf = 0
function THREAD:newFunction(func,holup)
stf = stf + 1
return function(...)
local t = multi:newSystemThread("STF"..stf,func,...)
return thread:newFunction(function()
return thread.hold(function()
if t.stab["returns"] then
local dat = t.stab.returns
t.stab.returns = nil
return unpack(dat)
end
end)
end,holup)()
end
end
function multi:newSystemThread(name,func,...)
local c = {}
c.name = name
c.ID=THREAD_ID
c.thread=lovr.thread.newThread(ThreadFileData)
c.thread:start(THREAD.dump(func),c.ID,c.name,...)
c.stab = THREAD.createStaticTable(name)
GLOBAL["__THREAD_"..c.ID] = {ID=c.ID,Name=c.name,Thread=c.thread}
GLOBAL["__THREAD_COUNT"] = THREAD_ID
THREAD_ID=THREAD_ID+1
return c
end
function lovr.threaderror(thread, errorstr)
print("Thread error!\n"..errorstr)
end
multi.integration.GLOBAL = GLOBAL
multi.integration.THREAD = THREAD
require("multi.integration.lovrManager.extensions")
print("Integrated lovr Threading!")
return {init=function()
return GLOBAL,THREAD
end}
+222
View File
@@ -0,0 +1,222 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
-- TODO make compatible with lovr
require("lovr.timer")
require("lovr.system")
require("lovr.data")
local socket = require("socket")
local multi, thread = require("multi").init()
local threads = {}
function threads.loadDump(d)
return loadstring(d:getString())
end
function threads.dump(func)
return lovr.data.newByteData(string.dump(func))
end
local fRef = {"func",nil}
local function manage(channel, value)
channel:clear()
if type(value) == "function" then
fRef[2] = THREAD.dump(value)
channel:push(fRef)
return
else
channel:push(value)
end
end
local function RandomVariable(length)
local res = {}
math.randomseed(socket.gettime()*10000)
for i = 1, length do
res[#res+1] = string.char(math.random(97, 122))
end
return table.concat(res)
end
local GNAME = "__GLOBAL_"
local proxy = {}
function threads.set(name,val)
if not proxy[name] then proxy[name] = lovr.thread.getChannel(GNAME..name) end
proxy[name]:performAtomic(manage, val)
end
function threads.get(name)
if not proxy[name] then proxy[name] = lovr.thread.getChannel(GNAME..name) end
local dat = proxy[name]:peek()
if type(dat)=="table" and dat[1]=="func" then
return THREAD.loadDump(dat[2])
else
return dat
end
end
function threads.waitFor(name)
if thread.isThread() then
return thread.hold(function()
return threads.get(name)
end)
end
while threads.get(name)==nil do
lovr.timer.sleep(.001)
end
local dat = threads.get(name)
if type(dat) == "table" and dat.init then
dat.init = threads.loadDump(dat.init)
end
return dat
end
function threads.package(name,val)
local init = val.init
val.init=threads.dump(val.init)
GLOBAL[name]=val
val.init=init
end
function threads.getCores()
return lovr.system.getProcessorCount()
end
function threads.kill()
error("Thread Killed!")
end
function threads.getThreads()
local t = {}
for i=1,GLOBAL["__THREAD_COUNT"] do
t[#t+1]=GLOBAL["__THREAD_"..i]
end
return t
end
function threads.getThread(n)
return GLOBAL["__THREAD_"..n]
end
function threads.getName()
return __THREADNAME__
end
function threads.getID()
return __THREADID__
end
function threads.sleep(n)
lovr.timer.sleep(n)
end
function threads.getGlobal()
return setmetatable({},
{
__index = function(t, k)
return THREAD.get(k)
end,
__newindex = function(t, k, v)
THREAD.set(k,v)
end
}
)
end
function threads.createTable(n)
local _proxy = {}
local function set(name,val)
if not _proxy[name] then _proxy[name] = lovr.thread.getChannel(n..name) end
_proxy[name]:performAtomic(manage, val)
end
local function get(name)
if not _proxy[name] then _proxy[name] = lovr.thread.getChannel(n..name) end
local dat = _proxy[name]:peek()
if type(dat)=="table" and dat[1]=="func" then
return THREAD.loadDump(dat[2])
else
return dat
end
end
return setmetatable({},
{
__index = function(t, k)
return get(k)
end,
__newindex = function(t, k, v)
set(k,v)
end
}
)
end
function threads.getConsole()
local c = {}
c.queue = lovr.thread.getChannel("__CONSOLE__")
function c.print(...)
c.queue:push{...}
end
function c.error(err)
c.queue:push{"ERROR in <"..__THREADNAME__..">: "..err,__THREADID__}
error(err)
end
return c
end
if not ISTHREAD then
local clock = os.clock
local lastproc = clock()
local queue = lovr.thread.getChannel("__CONSOLE__")
multi:newThread("consoleManager",function()
while true do
thread.yield()
dat = queue:pop()
if dat then
lastproc = clock()
print(unpack(dat))
end
if clock()-lastproc>2 then
thread.sleep(.1)
end
end
end)
end
function threads.createStaticTable(n)
local __proxy = {}
local function set(name,val)
if __proxy[name] then return end
local chan = lovr.thread.getChannel(n..name)
if chan:getCount()>0 then return end
chan:performAtomic(manage, val)
__proxy[name] = val
end
local function get(name)
if __proxy[name] then return __proxy[name] end
local dat = lovr.thread.getChannel(n..name):peek()
if type(dat)=="table" and dat[1]=="func" then
__proxy[name] = THREAD.loadDump(dat[2])
return __proxy[name]
else
__proxy[name] = dat
return __proxy[name]
end
end
return setmetatable({},
{
__index = function(t, k)
return get(k)
end,
__newindex = function(t, k, v)
set(k,v)
end
}
)
end
function threads.hold(n)
local dat
while not(dat) do
dat = n()
end
end
return threads
@@ -0,0 +1,141 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
local multi, thread = require("multi"):init()
local GLOBAL, THREAD = multi.integration.GLOBAL,multi.integration.THREAD
local function stripUpValues(func)
local dmp = string.dump(func)
if setfenv then
return loadstring(dmp,"IsolatedThread_PesudoThreading")
else
return load(dmp,"IsolatedThread_PesudoThreading","bt")
end
end
function multi:newSystemThreadedQueue(name)
local c = {}
function c:push(v)
table.insert(self,v)
end
function c:pop()
return table.remove(self,1)
end
function c:peek()
return self[1]
end
function c:init()
return self
end
GLOBAL[name or "_"] = c
return c
end
function multi:newSystemThreadedTable(name)
local c = {}
function c:init()
return self
end
GLOBAL[name or "_"] = c
return c
end
local setfenv = setfenv
if not setfenv then
if not debug then
multi.print("Unable to implement setfenv in lua 5.2+ the debug module is not available!")
else
setfenv = function(f, env)
return load(string.dump(f), nil, nil, env)
end
end
end
function multi:newSystemThreadedJobQueue(n)
local c = {}
c.cores = n or THREAD.getCores()*2
c.OnJobCompleted = multi:newConnection()
local jobs = {}
local ID=1
local jid = 1
local env = {}
setmetatable(env,{
__index = _G
})
local funcs = {}
function c:doToAll(func)
setfenv(func,env)()
return self
end
function c:registerFunction(name,func)
funcs[name] = setfenv(func,env)
return self
end
function c:pushJob(name,...)
table.insert(jobs,{name,jid,{...}})
jid = jid + 1
return jid-1
end
function c:isEmpty()
print(#jobs)
return #jobs == 0
end
local nFunc = 0
function c:newFunction(name,func,holup) -- This registers with the queue
local func = stripUpValues(func)
if type(name)=="function" then
holup = func
func = name
name = "JQ_Function_"..nFunc
end
nFunc = nFunc + 1
c:registerFunction(name,func)
return thread:newFunction(function(...)
local id = c:pushJob(name,...)
local link
local rets
link = c.OnJobCompleted(function(jid,...)
if id==jid then
rets = {...}
link:Destroy()
end
end)
return thread.hold(function()
if rets then
return unpack(rets) or multi.NIL
end
end)
end,holup),name
end
for i=1,c.cores do
multi:newThread("PesudoThreadedJobQueue_"..i,function()
while true do
thread.yield()
if #jobs>0 then
local j = table.remove(jobs,1)
c.OnJobCompleted:Fire(j[2],funcs[j[1]](unpack(j[3])))
else
thread.sleep(.05)
end
end
end)
end
return c
end
+90
View File
@@ -0,0 +1,90 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
package.path = "?/init.lua;?.lua;" .. package.path
local multi, thread = require("multi").init()
if multi.integration then
return {
init = function()
return multi.integration.GLOBAL, multi.integration.THREAD
end
}
end
local GLOBAL, THREAD = require("multi.integration.pesudoManager.threads"):init()
function multi:canSystemThread() -- We are emulating system threading
return true
end
function multi:getPlatform()
return "pesudo"
end
local function split(str)
local tab = {}
for word in string.gmatch(str, '([^,]+)') do
table.insert(tab,word)
end
return tab
end
THREAD.newFunction=thread.newFunction
local id = 0
function multi:newSystemThread(name,func,...)
GLOBAL["$THREAD_NAME"] = name
GLOBAL["$__THREADNAME__"] = name
GLOBAL["$THREAD_ID"] = id
--GLOBAL["$thread"] = thread
local env = {
GLOBAL = GLOBAL,
THREAD = THREAD,
THREAD_NAME = name,
__THREADNAME__ = name,
THREAD_ID = id,
thread = thread
}
local tab = [[_VERSION,io,os,require,load,debug,assert,collectgarbage,error,getfenv,getmetatable,ipairs,loadstring,module,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,xpcall,math,coroutine,string,table]]
tab = split(tab)
for i = 1,#tab do
env[tab[i]] = _G[tab[i]]
end
--setmetatable(env,{__index=env})
multi:newISOThread(name,func,env,...).OnError(function(self,msg)
print("ERROR:",msg)
end)
id = id + 1
end
-- System threads as implemented here cannot share memory, but use a message passing system.
-- An isolated thread allows us to mimic that behavior so if access data from the "main" thread happens things will not work. This behavior is in line with how the system threading works
print("Integrated Pesudo Threading!")
multi.integration = {} -- for module creators
multi.integration.GLOBAL = GLOBAL
multi.integration.THREAD = THREAD
require("multi.integration.pesudoManager.extensions")
return {
init = function()
return GLOBAL, THREAD
end
}
@@ -0,0 +1,96 @@
--[[
MIT License
Copyright (c) 2020 Ryan Ward
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
local function getOS()
if package.config:sub(1, 1) == "\\" then
return "windows"
else
return "unix"
end
end
local function INIT(env)
local THREAD = {}
local GLOBAL = {}
THREAD.Priority_Core = 3
THREAD.Priority_High = 2
THREAD.Priority_Above_Normal = 1
THREAD.Priority_Normal = 0
THREAD.Priority_Below_Normal = -1
THREAD.Priority_Low = -2
THREAD.Priority_Idle = -3
function THREAD.set(name, val)
GLOBAL[name] = val
end
function THREAD.get(name)
return GLOBAL[name]
end
function THREAD.waitFor(name)
print("Waiting",thread)
return thread.hold(function() return GLOBAL[name] end)
end
if getOS() == "windows" then
THREAD.__CORES = tonumber(os.getenv("NUMBER_OF_PROCESSORS"))
else
THREAD.__CORES = tonumber(io.popen("nproc --all"):read("*n"))
end
function THREAD.getCores()
return THREAD.__CORES
end
function THREAD.getConsole()
local c = {}
function c.print(...)
print(...)
end
function c.error(err)
error("ERROR in <"..GLOBAL["$__THREADNAME__"]..">: "..err)
end
return c
end
function THREAD.getThreads()
return {}--GLOBAL.__THREADS__
end
if os.getOS() == "windows" then
THREAD.__CORES = tonumber(os.getenv("NUMBER_OF_PROCESSORS"))
else
THREAD.__CORES = tonumber(io.popen("nproc --all"):read("*n"))
end
function THREAD.kill()
error("Thread was killed!")
end
function THREAD.getName()
return GLOBAL["$THREAD_NAME"]
end
function THREAD.getID()
return GLOBAL["$THREAD_ID"]
end
function THREAD.sleep(n)
thread.sleep(n)
end
function THREAD.hold(n)
return thread.hold(n)
end
return GLOBAL, THREAD
end
return {init = function()
return INIT()
end}
-2
View File
@@ -1,2 +0,0 @@
-- Planned system threaded objects
-- multi:newSystemThreadedConnection(name, protect)
+13
View File
@@ -0,0 +1,13 @@
-- We need to detect what enviroment we are running our code in.
return {
init = function()
if love then
return require("multi.integration.loveManager"):init()
else
if pcall(require,"lanes") then
return require("multi.integration.lanesManager"):init()
end
return require("multi.integration.pesudoManager"):init()
end
end
}
+38
View File
@@ -0,0 +1,38 @@
package = "multi"
version = "15.0-0"
source = {
url = "git://github.com/rayaman/multi.git",
tag = "v15.0.0",
}
description = {
summary = "Lua Multi tasking library",
detailed = [[
This library contains many methods for multi tasking. Features non coroutine based multi-tasking, coroutine based multi-tasking, and system threading (Requires use of an integration).
Check github for how to use.
]],
homepage = "https://github.com/rayaman/multi",
license = "MIT"
}
dependencies = {
"lua >= 5.1",
"lanes",
}
build = {
type = "builtin",
modules = {
["multi"] = "multi/init.lua",
["multi.compat.love2d"] = "multi/compat/love2d.lua",
["multi.integration.threading"] = "multi/integration/threading.lua",
["multi.integration.lanesManager"] = "multi/integration/lanesManager/init.lua",
["multi.integration.lanesManager.extensions"] = "multi/integration/lanesManager/extensions.lua",
["multi.integration.lanesManager.threads"] = "multi/integration/lanesManager/threads.lua",
["multi.integration.loveManager"] = "multi/integration/loveManager/init.lua",
["multi.integration.loveManager.extensions"] = "multi/integration/loveManager/extensions.lua",
["multi.integration.loveManager.threads"] = "multi/integration/loveManager/threads.lua",
["multi.integration.pesudoManager"] = "multi/integration/pesudoManager/init.lua",
["multi.integration.pesudoManager.extensions"] = "multi/integration/pesudoManager/extensions.lua",
["multi.integration.pesudoManager.threads"] = "multi/integration/pesudoManager/threads.lua",
["multi.integration.luvitManager"] = "multi/integration/luvitManager.lua",
--["multi.integration.networkManager"] = "multi/integration/networkManager.lua",
}
}
+42
View File
@@ -0,0 +1,42 @@
package = "multi"
version = "15.1-0"
source = {
url = "git://github.com/rayaman/multi.git",
tag = "V15.1.0",
}
description = {
summary = "Lua Multi tasking library",
detailed = [[
This library contains many methods for multi tasking. Features non coroutine based multi-tasking, coroutine based multi-tasking, and system threading (Requires use of an integration).
Check github for documentation.
]],
homepage = "https://github.com/rayaman/multi",
license = "MIT"
}
dependencies = {
"lua >= 5.1",
"lanes",
}
build = {
type = "builtin",
modules = {
["multi"] = "multi/init.lua",
["multi.compat.love2d"] = "multi/compat/love2d.lua",
["multi.compat.lovr"] = "multi/compat/lovr.lua",
["multi.integration.lanesManager"] = "multi/integration/lanesManager/init.lua",
["multi.integration.lanesManager.extensions"] = "multi/integration/lanesManager/extensions.lua",
["multi.integration.lanesManager.threads"] = "multi/integration/lanesManager/threads.lua",
["multi.integration.loveManager"] = "multi/integration/loveManager/init.lua",
["multi.integration.loveManager.extensions"] = "multi/integration/loveManager/extensions.lua",
["multi.integration.loveManager.threads"] = "multi/integration/loveManager/threads.lua",
--["multi.integration.lovrManager"] = "multi/integration/lovrManager/init.lua",
--["multi.integration.lovrManager.extensions"] = "multi/integration/lovrManager/extensions.lua",
--["multi.integration.lovrManager.threads"] = "multi/integration/lovrManager/threads.lua",
["multi.integration.pesudoManager"] = "multi/integration/pesudoManager/init.lua",
["multi.integration.pesudoManager.extensions"] = "multi/integration/pesudoManager/extensions.lua",
["multi.integration.pesudoManager.threads"] = "multi/integration/pesudoManager/threads.lua",
["multi.integration.luvitManager"] = "multi/integration/luvitManager.lua",
["multi.integration.threading"] = "multi/integration/threading.lua",
--["multi.integration.networkManager"] = "multi/integration/networkManager.lua",
}
}
-25
View File
@@ -1,25 +0,0 @@
-- set up the package
package.path="?/init.lua;?.lua;"..package.path
-- Import the libraries
multi = require("multi")
local GLOBAL, THREAD = require("multi.integration.lanesManager").init()
nGLOBAL = require("multi.integration.networkManager").init()
-- Act as a master node
master = multi:newMaster{
name = "Main", -- the name of the master
--noBroadCast = true, -- if using the node manager, set this to true to avoid double connections
--managerDetails = {"localhost",12345}, -- the details to connect to the node manager (ip,port)
}
master.OnError(function(name,err)
print(name.." has encountered an error: "..err)
end)
master.OnNodeConnected(function(name)
-- name is the name of the node that connected
end)
-- Starting the multitasker
settings = {
priority = 0, -- 0, 1 or 2
protect = false,
}
multi:threadloop(settings) -- both mainloop and threadloop can be used. one pirotizes threads where the other pirotizes multiobjs
--multi:mainloop(settings)
-16
View File
@@ -1,16 +0,0 @@
package.path="?/init.lua;?.lua;"..package.path
multi = require("multi")
local GLOBAL, THREAD = require("multi.integration.lanesManager").init()
nGLOBAL = require("multi.integration.networkManager").init()
node = multi:newNode{
allowRemoteRegistering = true, -- allows you to register functions from the master on the node, default is false
name = nil, -- default value
--noBroadCast = true, -- if using the node manager, set this to true to prevent the node from broadcasting
--managerDetails = {"localhost",12345}, -- connects to the node manager if one exists
}
settings = {
priority = 0, -- 1 or 2
stopOnError = true, -- if an actor crashes this will prevent it from constantly crashing over and over. You can leave this false and use multi.OnError to handle crashes as well
protect = true, -- always protect a node. Not really needed since all executed xode from a master is protected on execution to prevent issues.
}
multi:mainloop(settings)
-12
View File
@@ -1,12 +0,0 @@
package.path="?/init.lua;?.lua;"..package.path
multi = require("multi")
local GLOBAL, THREAD = require("multi.integration.lanesManager").init()
nGLOBAL = require("multi.integration.networkManager").init()
multi:nodeManager(12345) -- Host a node manager on port: 12345
print("Node Manager Running...")
settings = {
priority = 0, -- 1 or 2
protect = false,
}
multi:mainloop(settings)
-- Thats all you need to run the node manager, everything else is done automatically
+101 -32
View File
@@ -1,44 +1,113 @@
package.path="?.lua;?/init.lua;?.lua;?/?/init.lua;"..package.path --package.path = "./?/init.lua;"..package.path
local multi,thread = require("multi"):init() multi,thread = require("multi"):init()
-- Testing destroying and fixed connections func = thread:newFunction(function(count)
c = multi:newConnection() local a = 0
c1 = c(function() while true do
print("called 1") a = a + 1
end) thread.sleep(.5)
c2 = c(function() thread.pushStatus(a,count)
print("called 2") if a == count then break end
end) end
c3 = c(function() return "Done"
print("called 3")
end) end)
print(c1,c2.Type,c3) multi:newThread("test",function()
c:Fire() local ret = func(10)
c2:Destroy() local ret2 = func(15)
print(c1,c2.Type,c3) local ret3 = func(20)
c:Fire() ret.OnStatus(function(part,whole)
c1:Destroy() print("Ret1: ",math.ceil((part/whole)*1000)/10 .."%")
print(c1,c2.Type,c3) end)
c:Fire() ret2.OnStatus(function(part,whole)
print("Ret2: ",math.ceil((part/whole)*1000)/10 .."%")
end)
ret3.OnStatus(function(part,whole)
print("Ret3: ",math.ceil((part/whole)*1000)/10 .."%")
end)
thread.hold(ret2.OnReturn + ret.OnReturn + ret3.OnReturn)
print("Function Done!")
os.exit()
end)
-- Destroying alarms and threads --GLOBAL,THREAD = require("multi.integration.threading"):init() -- Auto detects your environment and uses what's available
local test = multi:newThread(function()
func2 = thread:newFunction(function()
thread.sleep(3)
print("Hello World!")
return true
end,true) -- set holdme to true
func2:holdMe(false) -- reset holdme to false
print("Calling func...")
print(func2())
test = thread:newFunction(function(a,b)
thread.sleep(1)
return a,b
end)
print(test(1,2).connect(function(...)
print(...)
end))
test:Pause()
print(test(1,2).connect(function(...)
print(...)
end))
test:Resume()
print(test(1,2).connect(function(...)
print(...)
end))
test = thread:newFunction(function()
return 1,2,nil,3,4,5,6,7,8,9
end,true)
print(test())
multi:newThread("testing",function()
print("#Test = ",test())
print(thread.hold(function()
print("Hello!")
return false
end,{
interval = 2,
cycles = 3
})) -- End result, 3 attempts within 6 seconds. If still false then timeout
print("held")
end).OnError(function(...)
print(...)
end)
sandbox = multi:newProcessor("Test Processor")
sandbox:newTLoop(function()
print("testing...")
end,1)
test2 = multi:newTLoop(function()
print("testing2...")
end,1)
sandbox:newThread("Test Thread",function()
local a = 0
while true do while true do
thread.sleep(1) thread.sleep(1)
print("Hello!") a = a + 1
print("Thread Test: ".. multi.getCurrentProcess().Name)
if a == 10 then
sandbox.Stop()
end end
end
end).OnError(function(...)
print(...)
end) end)
test.OnDeath(function() multi:newThread("Test Thread",function()
os.exit() -- This is the last thing called. while true do
thread.sleep(1)
print("Thread Test: ".. multi.getCurrentProcess().Name)
end
end).OnError(function(...)
print(...)
end) end)
local alarm = multi:newAlarm(4):OnRing(function(a) sandbox.Start()
print(a.Type)
a:Destroy()
print(a.Type)
test:Destroy()
end)
multi:lightloop() multi:mainloop()
+3
View File
@@ -0,0 +1,3 @@
return function objectTests(multi,thread)
print("Testing Alarms!")
end
+21
View File
@@ -0,0 +1,21 @@
package.path="../?.lua;../?/init.lua;../?.lua;../?/?/init.lua;"..package.path
--[[
This file runs all tests.
Format:
Expected:
...
...
...
Actual:
...
...
...
Each test that is ran should have a 5 second pause after the test is complete
The expected and actual should "match" (Might be impossible when playing with threads)
This will be pushed directly to the master as tests start existing.
]]
local multi, thread = require("multi"):init()
function runTest(path)
end