pecan icon indicating copy to clipboard operation
pecan copied to clipboard

Use Timer.delay(f,0) when resolving async coroutines

Open neimanpinchas opened this issue 11 months ago • 1 comments

I had an issue, I havn't yet resolved or narrowed down.

Utilizing this function

	@:pecan.accept static  function sleep(ms, ?cb:Int->Void, ?co):Int {
		trace("sleeping");
        Timer.delay(function() {
			trace("done sleeping");
			cb(1);
		}, ms);
		return 0;
	}

Which compiled to

Stt.sleep = function(ms,cb,co) {
	haxe_Log.trace("sleeping",{ fileName : "Stt.hx", lineNumber : 32, className : "Stt", methodName : "sleep"});
	haxe_Timer.delay(function() {
		haxe_Log.trace("done sleeping",{ fileName : "Stt.hx", lineNumber : 34, className : "Stt", methodName : "sleep"});
		cb(1);
	},ms);
	return 0;
};

Was running multiple times, when hooking in a debugger I found that cfgState was rewinded somehow to an earlier state, so when the callback is done it wwent back a step, I wasn't able to find anywhere in the code where it is modified.

In order to make the stacktrace smaller, I modified

,wakeupRet: function() {
		if(!this.expecting) {
			throw haxe_Exception.thrown("invalid state - can only return to Co in Expecting state");
		}
		this.expecting = false;
		this.ready = true;
		setTimeout(()=>{
			this.tick();
		},0);
		
	}

Interesting that the original problem disapeared.

neimanpinchas avatar Jan 14 '25 14:01 neimanpinchas

I''ve just for courtisy tried myself https://github.com/Aurel300/pecan/issues/16, I think it is related.

Basically if the callback is called before its callie returns then the tick iteration didn't finish yet, the while loop never seems the ready flag as false, before it is getting back true by wakeUp.

This also explains why my quick hack fixed it.

neimanpinchas avatar Jan 14 '25 14:01 neimanpinchas