Compile the thread code in JavaScript to reference concurrent. thread. js.

Source: Internet
Author: User

Compile the thread code in JavaScript to reference concurrent. thread. js.

Http://jsthread.sourceforge.net/cgi-bin/wiki/wiki.cgi#p0

Download and use the source code immediately! Assume that you have saved the downloaded source code to a folder named concurrent. thread. js. Before performing any operations, run the following program. This is a simple function implementation:

<script type="text/javascript" src="Concurrent.Thread.js"></script>
<script type="text/javascript">
Concurrent.Thread.create(function(){
var i = 0;
while ( 1 ) {
document.body.innerHTML += i++ + "<br>";
}
});
</script>

Execute this program to display the numbers starting from 0 in sequence. They appear one by one. You can view them on the screen. Now let's take a closer look at the code. The while (1) condition is applied to create a loop that won't be aborted. Normally, A JavaScript program that keeps using one thread and is the only thread will cause the browser to look like frozen, and naturally it will not allow you to scroll the screen. So why does the above program allow you to do this? The key lies in the concurrent. thread. Create () statement above while (1). This is a method provided by this library, which can create a new thread. The function passed in as a parameter is executed in this new thread. Let's fine tune the program as follows:

<script type="text/javascript" src="Concurrent.Thread.js"></script>
<script type="text/javascript">
function f ( i ){
while ( 1 ) {
document.body.innerHTML += i++ + "<br>";
}
}
Concurrent.Thread.create(f, 0);
Concurrent.Thread.create(f, 100000);
</script>

In this program, a new function f () can repeatedly display numbers, which is defined at the beginning of the program segment. Then, the F () parameter is used to call the CREATE () method twice, the second parameter passed to the CREATE () method will be passed to F () without modification (). Execute this program, first you will see some decimal places starting from 0, followed by some large numbers starting from 100,000, and then followed by the first decimal order number. You can observe that the program is alternately displaying decimals and large numbers, which means that the two threads are running at the same time.

Let me demonstrate another usage of concurrent. thread. The preceding example calls the CREATE () method to create a new thread. This can also be achieved without calling any APIs in the library. For example, the previous example can be written as follows:

<script type="text/javascript" src="Concurrent.Thread.js"></script>
<script type="text/x-script.multithreaded-js">
var i = 1;
while ( 1 ) {
document.body.innerHTML += i++ + "<br>";
}
</script>

In the script tag, it is easy to write an infinite loop with JavaScript. You should note the type attribute in the tag, which is a strange value (text/X-script. multithreaded-js). If this attribute is placed in the script tag, then concurrent. thread will execute the program between labels in a new thread. You should remember that, in this example, the concurrent. Thread library must be included.

With concurrent. thread, it is possible to switch the execution environment between threads freely, even if your program is very long and has a strong continuity. We can briefly discuss how to perform this operation. In short, code conversion is required. Roughly speaking, first convert the function passed to create () into a string, and then rewrite it until it can be executed in batches. Then these programs can be executed gradually according to the scheduler. The scheduler is responsible for coordinating multithreading. In other words, it can make adjustments as appropriate so that every modified function can run at the same opportunity. Concurrent. Thread does not actually create a new thread. It only simulates a multi-threaded environment based on the original single thread.

Although the converted functions seem to run in different threads, only one thread is actually doing this. Executing synchronous communication in the converted function will still cause browser freezing. You may think that the previous problems have not been solved. However, you don't have to worry about it. Concurrent. Thread provides a custom communication library that uses JavaScript asynchronous communication methods. It is designed to allow other threads to run when a thread is waiting for the response from the server. The communication stock is under concurrent. thread. HTTP. Its usage is as follows:

<script type="text/javascript" src="Concurrent.Thread.js"></script>
<script type="text/x-script.multithreaded-js">
var req = Concurrent.Thread.Http.get(url, ["Accept", "*"]);
if (req.status == 200) {
alert(req.responseText);
} else {
alert(req.statusText);
}
</script>

The get () method, as its name implies, can get the content of the specified URL through the http get method, it takes the target URL as the first parameter, use an array representing the HTTP Request Header as the second optional parameter. The get () method interacts with the server. When the server responds, an XMLHTTPRequest object is returned as the return value. When the get () method returns, the server response has been received, so there is no need to use the callback function to receive the result. Naturally, you don't have to worry about freezing the browser when the program waits for the response from the server. In addition, there is a post () method that can be used to send data to the server:

<script type="text/javascript" src="Concurrent.Thread.js"></script>
<script type="text/x-script.multithreaded-js">
var req = Concurrent.Thread.Http.post(url, "key1=val1&key2=val2");
alert(req.statusText);
</script>

The post () method uses the destination URL as the first parameter and the content to be sent as the second parameter. Like the get () method, you can also use the request header as the third optional parameter.

If you use this communication library to implement the getarticle () method in the first example, you will soon be able to write getarticlewithcache () and backgroundload () using the simple method in the example at the beginning of the article () and other functions that call the getarticle () method. Even if the version of backgroundload () is reading article data, as shown in the following example, another thread can respond to user requests, so the browser will not be frozen. Now, how practical is multithreading used in JavaScript?

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.