blob: 84cb1f561a782b3586aff37d25d77ab75889a2d3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
---
title: navigator.hardwareConcurrency
slug: orphaned/Web/API/NavigatorConcurrentHardware/hardwareConcurrency
translation_of: Web/API/NavigatorConcurrentHardware/hardwareConcurrency
original_slug: Web/API/NavigatorConcurrentHardware/hardwareConcurrency
---
<p>{{APIRef("HTML DOM")}}</p>
<p>{{AvailableInWorkers}}</p>
<p><code><strong>navigator.hardwareConcurrency </strong>指明当前浏览器环境所拥有的CPU核心数,这来自于操作系统提供的API来获取。</code></p>
<h2 id="用法">用法</h2>
<pre class="syntaxbox"><em>CPU核心数</em>= window.navigator.hardwareConcurrency
</pre>
<h2 id="Value">Value</h2>
<p>A {{jsxref("Number")}} indicating the number of logical processor cores.</p>
<p>Modern computers have multiple physical processor cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may offer eight <strong>logical processor cores</strong>, for example. The number of logical processor cores can be used to measure the number of threads which can effectively be run at once without them having to context switch.</p>
<p>The browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of {{domxref("Worker")}}s that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system.</p>
<h2 id="Examples">Examples</h2>
<p>In this example, one {{domxref("Worker")}} is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a Boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use. This creates a pool of workers we can use to process requests later.</p>
<pre class="brush: js">let workerList = [];
for (let i = 0; i < window.navigator.hardwareConcurrency; i++) {
let newWorker = {
worker: new Worker('cpuworker.js'),
inUse: false
};
workerList.push(newWorker);
}</pre>
<h2 id="Specification">Specification</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('HTML WHATWG', '#navigatorconcurrenthardware', 'NavigatorConcurrentHardware')}}</td>
<td>{{Spec2('HTML WHATWG')}}</td>
<td>Initial definition.</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<div>
<p>{{Compat("api.NavigatorConcurrentHardware.hardwareConcurrency")}}</p>
</div>
<h2 id="See_also">See also</h2>
<ul>
<li>{{domxref("Navigator")}}</li>
<li>{{domxref("WorkerNavigator")}}</li>
</ul>
|