Each plugin has its own global Lua environment for storing global variables (those not declared via a "local" statement). All invocations of plugin scripts and background tasks execute within that environment, so if one script execution sets a global, that global's value will be seen by future script invocations and background tasks. That environment is re-initialized (and all existing global variables discarded) when the plugin is loaded or reloaded.
Lua has a special built-in global _G whose value is a table containing all global variables. So a script can reference either the global "x" or "_G.x" -- they refer to the same global variable.
To terminate a background a plugin's background task when the plugin is removed, reloaded, or disabled or when LR is shutdown, maintain a global "running". When true, the task continues to run, but when false, the task should exit. The task should test "running" periodically. Define scripts for the Info.lua's LrShutdownPlugin, LrDisablePlugin, and LrShutdownApp that set "running" to false.