Thread in Javascript

Source: Internet
Author: User

Today, I am arguing with a colleague about the thread mechanism in the middle of javascripe. He argues that JavaScript has a thread, even if the Event Callback In The Middle Of Javascript is the implementation of the thread, I personally think there is no thread mechanism in javascript:

The reasons are as follows:

Introduced by <proficient in Javascript> JOHN resig:

  1. <SCRIPT>
  2. <! --
  3. While (! Window. Loaded );
  4. // Some operation
  5. Window. Alert ();
  6. -->
  7. </SCRIPT>

The purpose of this Code is to block the current JS thread. After the page is fully loaded, execute the following operations, that is, "synchronization", but the effect is that the browser is suspended or dead. It can be seen that in JS, the wait cannot be paused by loop; it can be seen that the callback must be used in early JavaScript to achieve this effect, namely:

  1. Wndow. onload = funcrion (){
  2. // Some operation
  3. }

However, callback is not the basis for supporting multithreading in JS language. We know that callback message mechanism is supported in windows; when we click a button, the system will call the event processing function, in the middle of windows, I want to bind a processing function to the start of the click event to maintain an event processing table, A click event in a space in the table corresponds to a function pointer for processing functions. When an event is clicked, the function pointer pointing to is called;

 

What is thread? I think we should start with a multi-threaded operating system. multithreading means that multiple processing processes are executed in turn, and this alternate time slice is very short, as short as we humans cannot perceive, this is why a single processor can also execute threads concurrently, and the callback we see above is actually like a method call, after the processor function is called, return to the original program segment for further execution. I think this is similar to the interrupt processing in the operating system.

Concept: We know that interrupt processing is supported by hardware. In a single processor system, multithreading is implemented by the operating system. Under my multi-threaded operating system, the operating system maintains multiple state thread queues and determines the Rotation Algorithm Used to switch between threads; he uses the rewrite time interrupt processor to call the process (thread) manager at the interval of a time slice to adjust the conversion and execution between the thread and the process. This shows that, the callback function similar to the interrupt processing function does not prove the existence of the thread (because the relationship between the two can be clearly seen from the above );

The following example can also clearly prove the so-called "Thread" of JS ":

  1. <Script language = "JavaScript">
  2. <! --
  3. FunctionMain (){
  4. For(VaRIndex = 0; index <10; index ++ ){
  5. Alert ("main thread ");
  6. SetTimeout (secondary, 20 );
  7. }
  8. }
  9. FunctionSecondary (){
  10. Alert ("secondary ");
  11. }
  12. Main ();
  13. -->
  14. </SCRIPT>

Because there is no process concept, it should have been executed alternately by the main and secondary here, and it has become the greedy scheduling after executing the main and then executing the secondary; then, in this understanding, there is no thread concept in Javascript. How can we implement the thread mechanism on our own? It is like how we implement the thread concept in the interrupt processing mechanism; since the system (JS engine) does not maintain the thread list and Scheduling for us, we can implement the scheduling algorithm and)

 

  1. <Script language = "JavaScript">
  2. <! --
  3. VaRThread_one_time = 0;
  4. VaRThread_two_time = 0;
  5. FunctionThread_one (){
  6. Thread_one_time ++;
  7. Alert (thread_one_time );
  8. }
  9. FunctionThread_two (){
  10. Thread_two_time ++;
  11. Alert (thread_two_time );
  12. }
  13. }
  14. Setinterval (FIG, 100 );
  15. Setinterval (FIG, 100 );
  16. -->
  17. </SCRIPT>

Here, we can see that two subprograms are executed alternately. In fact, if we look at them from the thread's perspective, there are three threads here, one is thread_one, the other is thread_two, and the other is main_thread (but the execution has been completed). Don't believe it. You can simply add and modify it as follows:

  1. <Script language = "JavaScript">
  2. <! --
  3. VaR thread_one_time = 0;
  4. VaR thread_two_time = 0;
  5. Function thread_one (){
  6. Thread_one_time ++;
  7. Alert (thread_one_time );
  8. }
  9. Function thread_two (){
  10. Thread_two_time ++;
  11. Alert (thread_two_time );
  12. }
  13. Setinterval (FIG, 100 );
  14. Setinterval (FIG, 100 );
  15. For (VAR I = 0; I <10; I ++ ){
  16. Alert (I + "Main ");
  17. }
  18. -->
  19. </SCRIPT>

 

The main program here can be regarded as a greedy main thread, which is equivalent to the Process Manager in the middle of the Operating System (implemented by the time interrupt processor). It schedules and switches to manage the thread queue of the entire system, the "scheduling algorithm" used here is very simple, that is, 100 seconds of time slice rotation, no priority, no interruption, No ........,

= JS process implementation code:

Thread. JS:

  1. /**
  2. * Thread management class
  3. * @ Author zxub 2006-06-12
  4. */
  5. Function thread (_ task, _ delay, _ times)
  6. {
  7. This. runflag = false;
  8. This. busyflag = false;
  9. This. taskargs = array. Prototype. Slice. Call (arguments, 3 );
  10. If (_ times! = Undefined)
  11. {
  12. This. Times = _ times;
  13. }
  14. Else
  15. {
  16. This. Times = 1;
  17. }
  18. VaR _ point = this;
  19. This. timerid =-1;
  20. This. Start = function ()
  21. {
  22. If (this. runflag = false)
  23. {
  24. This. timerid = Window. setinterval (_ point. Run, _ delay );
  25. This. runflag = true;
  26. }
  27. }
  28. This. Run = function ()
  29. {
  30. If (_ point. busyflag) return;
  31. If (_ point. Times =-1) // Infinite Loop
  32. {
  33. _ Task (_ point. taskargs );
  34. }
  35. Else if (_ point. Times> 0)
  36. {
  37. _ Task (_ point. taskargs );
  38. _ Point. Times-= 1;
  39. If (_ point. Times = 0)
  40. {
  41. Window. clearinterval (this. timerid );
  42. }
  43. }
  44. }
  45. This. Sleep = function ()
  46. {
  47. This. busyflag = true;
  48. }
  49. This. Resume = function ()
  50. {
  51. This. busyflag = false;
  52. }
  53. This. Abort = function ()
  54. {
  55. Window. clearinterval (this. timerid );
  56. }
  57. }

Thread.html:

  1. <HTML>
  2. <Head>
  3. <Title> test </title>
  4. <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
  5. <SCRIPT type = "text/JavaScript" src = "thread. js"> </SCRIPT>
  6. <Style type = "text/CSS">
  7. <! --
  8. Body, TR, TD {font-size: 12px ;}
  9. -->
  10. </Style>
  11. </Head>
  12. <Body>
  13. <SCRIPT>
  14. VaR func = function (_ o)
  15. {
  16. Document. getelementbyid (_ o). innerhtml = parseint (document. getelementbyid (_ o). innerhtml) + 1;
  17. }
  18. VaR T1 = new thread (func, 50,121, "T1 ");
  19. VaR t2 = new thread (func, 200,20, "T2 ");
  20. </SCRIPT>
  21. <Input type = "button" value = "start1" onclick = 'T1. Start (); '> </input>
  22. <Input type = "button" value = "sleep1" onclick = 'T1. Sleep (); '> </input>
  23. <Input type = "button" value = "resume1" onclick = 'T1. Resume (); '> </input>
  24. <Input type = "button" value = "abort1" onclick = 'T1. Abort (); '> </input>
  25. <Input type = "button" value = "start2" onclick = 't2. Start (); '> </input>
  26. <Input type = "button" value = "sleep2" onclick = 't2. Sleep (); '> </input>
  27. <Input type = "button" value = "resume2" onclick = 't2. Resume (); '> </input>
  28. <Input type = "button" value = "abort2" onclick = 't2. Abort (); '> </input>
  29. <Div id = "T1"> 0 </div> | <Div id = "T2"> 0 </div>
  30. <Input type = "button" value = "t1.timerid" onclick = 'alert (t1.timerid); '> </input>
  31. <Input type = "button" value = "t2.timerid" onclick = 'alert (t2.timerid); '> </input>
  32. </Body>
  33. </Html>

The first thread I came into contact with was the Operating System. Due to the special nature of JS, some people say that the language of toys is not rigorous, while others say it is flexible and mixed, therefore, I have explained some of my views on JS threads in conjunction with the operating system. I am not sure that I am right, or that I am not sure what I mean, many times, the language cannot express your own understanding. If you have a deep understanding of it, you will have to work harder to express it to others. I have always been confused about Js, closure, object-oriented initialization, there are many places worth exploring, hope to learn from you; (refer to the source for conversion, csdn Corey)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.