Hijack Variable Mutator

BlitzMax Forums/BlitzMax Programming/Hijack Variable Mutator

BLaBZ(Posted 2013) [#1]
This is going to seem like an odd question but I'll explain in a bit...

Is it possible to "hijack" the setting of a variable ie:

local x:int

x = 12'Hijack this

Function xSet(in:int, varptr out:int)
'do something before
out = in'set variable
'do something after
end function



I'd like to do this because I want to create a "auto-threader" we lock\unlock mutexes when variables are being set.


Yasha(Posted 2013) [#2]
You can't hijack = because there's nothing to hook into. But you can replace all relevant uses of = with a setter function:

Function Set(l:Object Var, r:Object)
    'stuff before
    l = r
    'stuff after
End Function

a = b    'WRONG
Set a, b    'Yay


Pretty close but you can't overload the operator syntactically: you must write it out.

Automatically locking and unlocking mutexes could potentially lead to a massive performance hit though, potentially outweighing the benefits you get from threading. Locks really ought to be explicit so you can feel bad every time you use one and try to think of ways to remove them.

The only real way to get performance out of multithreading is to not share data at all; divide your task into subtasks that don't need to refer to each other until they're done and reporting in. Locks are a hacky patch, not a solution.