Quantcast
Channel: How is Javascript single threaded? - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by brixdan for How is Javascript single threaded?

$
0
0

Definition - Multithreading:Multithreading is a type of execution model that allows multiple threads to exist within the context of a process such that they execute independently but share their process resources.In that sense JavaScript is totally multithreaded thing:

   let Ar;    Ar = []    function multiapp(ar,w,n) {        ar.clear;        for (let i = 0; i < n; i++)            setTimeout(function(){ar.push(w)},i);    }+function fn() {        //Thread 1        setTimeout(() => multiapp(Ar,1,10),100)        //Thread 2        setTimeout(() => multiapp(Ar,2,10),100)    }()    setTimeout(function(){console.log('Ar(1) = ', Ar.filter((i) => i == 1).length,'Ar(2) = ', Ar.filter((i) => i == 2).length,' Ar = ',Ar)},2000);//Ar(1) =  10 Ar(2) =  10  Ar =  [ 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 ]`

Apparently thread 1 starts and executes its own stack, independently of thread 2. Two threads share access to the same context object instance Ar and modify it in unknown fashion. Behaves exactly as Java with atomic primitives.


Viewing all articles
Browse latest Browse all 7

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>