You Got A Question? Ask    GNOME Community!


Mimic Threads in GJS with Yield

Scripting in GJS is so easy and much stronger than Bash. First option is always Python, but what if we don’t know Python?

This is a GJS script, that mimics threads with Yield operator.

#!/bin/gjs

var myApp =  new function() {

	this.threads = new Array ()	

	this._myThread = function ( threadN ) {

		for ( var i =0; i<4; i++ ) {
			print ( i+ " " +threadN )
			yield
		}
	}

	this._createThreads = function() {

		this.threads.push( new this._myThread ('thread_1') )
		this.threads.push( new this._myThread ('thread_2') )
		this.threads.push( new this._myThread ('thread_3') )
		this.threads.push( new this._myThread ('thread_4') )
	}

	this._myScheduler = function() {

		while (this.threads.length) {
			var thread = this.threads.shift()
			try {
				thread.next()
				this.threads.push(thread)
			} catch(e if e instanceof StopIteration) {
				//print ( e )			
			}
		}	

	}

	this.startMyApp = function () {
		this._createThreads()
		this._myScheduler()
	}	

}

myApp.startMyApp ()

Output:

0 thread_1
0 thread_2
0 thread_3
0 thread_4
1 thread_1
1 thread_2
1 thread_3
1 thread_4
2 thread_1
2 thread_2
2 thread_3
2 thread_4
3 thread_1
3 thread_2
3 thread_3
3 thread_4

I have written another small tutorial in how you can spawn sync/async processes with GJS.

If you async coding, don’t forget to use chains, to make sure that your functions will be executed in correct order.

funcA_Async () 
	if ( !e )
	funcB_Async ()
		if ( !e ) 
		funcC_Async ()

Yield is a bit risky because it’s not es6, but there are bigger breaks in gjs and introspection than spidermonkey.


 
  We can't watch comments unless G+ provides an API or if you send a notification, e.g +World Of Gnome
     Sometimes is better to place your questions on GNOME Community