Session variables are implemented as a thread-local memory area which accessed directly, without taking any locks. What is even more important is that there is a lot of implicit and explicit assumptions that session variable values do not change during a statement execution. For example, imagine changing the SQL mode, or connection's character set or some buffer size in the middle of a statement. So it does not look that simple in the general case.
What we can do to circumvent that is to delay the actual update until the end of the current statement execution (if any) in the target thread, by updating a separate per-thread copy of thd->variables, and then replacing the actual session variable values by that copy when the statement completes. That, of course, can only be implemented as a patch, I don't see a safe way to implement it as a UDF.
Session variables are implemented as a thread-local memory area which accessed directly, without taking any locks. What is even more important is that there is a lot of implicit and explicit assumptions that session variable values do not change during a statement execution. For example, imagine changing the SQL mode, or connection's character set or some buffer size in the middle of a statement. So it does not look that simple in the general case.
What we can do to circumvent that is to delay the actual update until the end of the current statement execution (if any) in the target thread, by updating a separate per-thread copy of thd->variables, and then replacing the actual session variable values by that copy when the statement completes. That, of course, can only be implemented as a patch, I don't see a safe way to implement it as a UDF.