This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
immibis's profile picture

Basic background thread API

Started by immibis, 17 August 2012 - 12:53 PM
immibis #1
Posted 17 August 2012 - 02:53 PM
Code: http://pastebin.com/KYtYxqHh

This adds one function, os.startThread(func, blockTerminate) which starts a new background thread (actually a coroutine, similar to what the parallel API does) independent of any existing threads. blockTerminate defaults to false (which allows Ctrl-T). Set it to true to block Ctrl-T from affecting that thread.

It should be loaded like any other program, not using os.loadAPI.

Since the actual thread API needs to run its own event loop, it cannot stop running until there are no threads left (all threads, including the main one, run "inside" the API). For this reason, it will normally start a thread which runs the shell. If the API is being loaded from a program, you can override this by creating a function called threadMain before loading the API.

Example use:

function testThread1()
 while true do
  os.sleep(2)
  print("Thread 1 (2 second interval)")
 end
end

function testThread2()
 while true do
  os.sleep(3)
  print("Thread 2 (3 second interval)")
 end
end

function threadMain()
  os.startThread(testThread1)
  os.startThread(testThread2)
  sleep(10)
  print("Ten seconds have passed.")
  -- threadMain returns, leaving only the two threads we just created running
  -- Ctrl-T will terminate both of those and then the thread API will exit, as there
  -- are no more threads.
end

shell.run("/thread-api") -- Or however you want to run the API
Melerion #2
Posted 10 October 2012 - 05:15 AM
This is what I've been looking for.

Nice, clean and simple to use and one of the few APIs in here that are actually useful.


Thanks for sharing.