zForth icon indicating copy to clipboard operation
zForth copied to clipboard

Is `handle_char` thread-safe?

Open phkeese opened this issue 6 months ago • 1 comments

Hello,

I noticed that handle_char uses a static buffer to buffer words, which sounds like it could cause issues when running two instances on two different threads:

static void handle_char(zf_ctx *ctx, char c)
{
	// Static buffer, shared between threads.
	static char buf[32];
	static size_t len = 0;

	if(ctx->input_state == ZF_INPUT_PASS_CHAR) {

		ctx->input_state = ZF_INPUT_INTERPRET;
		run(ctx, &c);

	} else if(c != '\0' && !isspace(c)) {

		if(len < sizeof(buf)-1) {
 			// Buffer access, not synchronized.
			buf[len++] = c;
			buf[len] = '\0';
		}

	} else {

		if(len > 0) {
			len = 0;
			handle_word(ctx, buf);
		}
	}
}

I can't test if this actually breaks in the real world right now, but this sounds like a potential race condition under true parallelism?

Best, Philipp

phkeese avatar Aug 15 '25 09:08 phkeese

Absolutely true, this is not at all thread safe.

The original zForth implementation supported only one global/static instance, support for multiple instances was only added fairly recently. these static buffers should be moved into the zf_ctx context instead.

There's also one static buffer in op_name(), this should ideally be moved outside into the call sites .

zevv avatar Aug 15 '25 09:08 zevv