3 ms·
Those aren't global variables; they're just variables. They are statically allocated, which you would think would lead to the problems you describe. But multi
by kragen 7y ago
Those aren't global variables; they're just variables. They are statically allocated, which you would think would lead to the problems you describe. But multithreaded Forth systems traditionally use cooperative rather than preemptive multithreading, and since VADD doesn't invoke any words that can yield to another thread, it can be assured that no other instances of VADD will mess with its variables while it's running. So that problem doesn't actually exist unless you're using something like GForth's experimental pthreads interface. In that case you could define the variables as "user variables" (TLS, in more widespread terminology) as well as the possibility of making them stack-allocated variables as you suggest.
I like stack-allocated variables, and they'd be the obviously correct solution in a language like C; but ANS Forth doesn't have them (oh, I see they've been added in Forth-2012; thank you!), they make it harder to factor words, and some of the other problems they solve in Algol-family and Lisp-family languages have other solutions in Forth, so the case for them is not as strong.
Also, traditionally, multithreaded Forth systems were multiuser; each task had its own dictionary. So a fourth way to avoid the problem (in addition to procedure-local variables, cooperative multitasking, and user variables) is to load the definitions above after spawning the potentially interfering task rather than before.