├── .gitignore ├── Cargo.toml ├── LICENSE-MIT ├── .appveyor.yml ├── README.md ├── .travis.yml ├── LICENSE-APACHE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "core_affinity" 3 | version = "0.8.3" 4 | authors = ["Philip Woods "] 5 | description = "Manages CPU affinities" 6 | readme = "README.md" 7 | license = "MIT OR Apache-2.0" 8 | documentation = "https://docs.rs/core_affinity/" 9 | homepage = "https://github.com/Elzair/core_affinity_rs" 10 | repository = "https://github.com/Elzair/core_affinity_rs" 11 | keywords = ["affinity", "thread-affinity", "cpu", "core"] 12 | categories = ["os"] 13 | 14 | [dependencies] 15 | num_cpus = "^1.14.0" 16 | 17 | [target.'cfg(any(target_os = "android", target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd"))'.dependencies] 18 | libc = "^0.2.30" 19 | 20 | [target.'cfg(target_os = "windows")'.dependencies] 21 | winapi = { version = "^0.3.9", features = ["processthreadsapi", "winbase"] } 22 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /.appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - TARGET: i686-pc-windows-gnu 4 | CHANNEL: stable 5 | - TARGET: x86_64-pc-windows-gnu 6 | CHANNEL: stable 7 | 8 | - TARGET: i686-pc-windows-gnu 9 | CHANNEL: beta 10 | - TARGET: x86_64-pc-windows-gnu 11 | CHANNEL: beta 12 | 13 | - TARGET: i686-pc-windows-gnu 14 | CHANNEL: nightly 15 | - TARGET: x86_64-pc-windows-gnu 16 | CHANNEL: nightly 17 | 18 | - TARGET: i686-pc-windows-msvc 19 | CHANNEL: stable 20 | - TARGET: x86_64-pc-windows-msvc 21 | CHANNEL: stable 22 | 23 | - TARGET: i686-pc-windows-msvc 24 | CHANNEL: beta 25 | - TARGET: x86_64-pc-windows-msvc 26 | CHANNEL: beta 27 | 28 | - TARGET: i686-pc-windows-msvc 29 | CHANNEL: nightly 30 | - TARGET: x86_64-pc-windows-msvc 31 | CHANNEL: nightly 32 | 33 | install: 34 | - curl -sSf -o rustup-init.exe https://win.rustup.rs 35 | - rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y 36 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 37 | - rustc -Vv 38 | - cargo -V 39 | 40 | build: false 41 | 42 | test_script: 43 | - cargo build 44 | - cargo test 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | `core_affinity_rs` is a Rust crate for managing CPU affinities. It currently supports Linux, Mac OSX, and Windows. 2 | 3 | [Documentation](https://docs.rs/core_affinity) 4 | 5 | # Example 6 | 7 | This example shows how create a thread for each available processor and pin each thread to its corresponding processor. 8 | 9 | ```rust 10 | extern crate core_affinity; 11 | 12 | use std::thread; 13 | 14 | // Retrieve the IDs of all cores on which the current 15 | // thread is allowed to run. 16 | // NOTE: If you want ALL the possible cores, you should 17 | // use num_cpus. 18 | let core_ids = core_affinity::get_core_ids().unwrap(); 19 | 20 | // Create a thread for each active CPU core. 21 | let handles = core_ids.into_iter().map(|id| { 22 | thread::spawn(move || { 23 | // Pin this thread to a single CPU core. 24 | let res = core_affinity::set_for_current(id); 25 | if (res) { 26 | // Do more work after this. 27 | } 28 | }) 29 | }).collect::>(); 30 | 31 | for handle in handles.into_iter() { 32 | handle.join().unwrap(); 33 | } 34 | ``` 35 | 36 | # Platforms 37 | 38 | `core_affinity_rs` should work on Linux, Windows, Mac OSX, FreeBSD, NetBSD, and Android. 39 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: stable 3 | 4 | install: 5 | - if [ -z "$NO_ADD" ]; then rustup target add "$TARGET"; fi 6 | 7 | script: 8 | - cargo build --verbose --target "$TARGET" 9 | - if [ "$RUN" == "1" ]; then cargo test --verbose --target "$TARGET"; fi 10 | 11 | matrix: 12 | include: 13 | # Linux 14 | # gnu 15 | # i686 16 | # stable 17 | - env: TARGET=i686-unknown-linux-gnu RUN=1 18 | rust: stable 19 | addons: 20 | apt: 21 | packages: 22 | - gcc-multilib 23 | # beta 24 | - env: TARGET=i686-unknown-linux-gnu RUN=1 25 | rust: beta 26 | addons: 27 | apt: 28 | packages: 29 | - gcc-multilib 30 | # nightly 31 | - env: TARGET=i686-unknown-linux-gnu RUN=1 32 | rust: nightly 33 | addons: 34 | apt: 35 | packages: 36 | - gcc-multilib 37 | # x86_64 38 | # stable 39 | - env: TARGET=x86_64-unknown-linux-gnu RUN=1 NO_ADD=1 40 | rust: stable 41 | # beta 42 | - env: TARGET=x86_64-unknown-linux-gnu RUN=1 NO_ADD=1 43 | rust: beta 44 | # nightly 45 | - env: TARGET=x86_64-unknown-linux-gnu RUN=1 NO_ADD=1 46 | rust: nightly 47 | # arm 48 | # stable 49 | - env: TARGET=arm-unknown-linux-gnueabihf 50 | rust: stable 51 | # beta 52 | - env: TARGET=arm-unknown-linux-gnueabihf 53 | rust: beta 54 | # nightly 55 | - env: TARGET=arm-unknown-linux-gnueabihf 56 | rust: nightly 57 | # aarch64 58 | # stable 59 | - env: TARGET=aarch64-unknown-linux-gnu 60 | rust: stable 61 | # beta 62 | - env: TARGET=aarch64-unknown-linux-gnu 63 | rust: beta 64 | # nightly 65 | - env: TARGET=aarch64-unknown-linux-gnu 66 | rust: nightly 67 | # mips 68 | # stable 69 | - env: TARGET=mips-unknown-linux-gnu 70 | rust: stable 71 | # beta 72 | - env: TARGET=mips-unknown-linux-gnu 73 | rust: beta 74 | # nightly 75 | - env: TARGET=mips-unknown-linux-gnu 76 | rust: nightly 77 | # musl 78 | # i686 79 | # stable 80 | - env: TARGET=i686-unknown-linux-musl RUN=1 81 | rust: stable 82 | addons: 83 | apt: 84 | packages: 85 | - gcc-multilib 86 | # beta 87 | - env: TARGET=i686-unknown-linux-musl RUN=1 88 | rust: beta 89 | addons: 90 | apt: 91 | packages: 92 | - gcc-multilib 93 | # nightly 94 | - env: TARGET=i686-unknown-linux-musl RUN=1 95 | rust: nightly 96 | addons: 97 | apt: 98 | packages: 99 | - gcc-multilib 100 | # x86_64 101 | # stable 102 | - env: TARGET=x86_64-unknown-linux-musl RUN=1 103 | rust: stable 104 | # beta 105 | - env: TARGET=x86_64-unknown-linux-musl RUN=1 106 | rust: beta 107 | # nightly 108 | - env: TARGET=x86_64-unknown-linux-musl RUN=1 109 | rust: nightly 110 | # aarch64 111 | # stable 112 | # - env: TARGET=aarch64-unknown-linux-musl 113 | # rust: stable 114 | # beta 115 | # - env: TARGET=aarch64-unknown-linux-musl 116 | # rust: beta 117 | # nightly 118 | - env: TARGET=aarch64-unknown-linux-musl 119 | rust: nightly 120 | # Mac OS X 121 | # i686 122 | # stable 123 | - os: osx 124 | env: TARGET=i686-apple-darwin RUN=1 125 | rust: stable 126 | # beta 127 | - os: osx 128 | env: TARGET=i686-apple-darwin RUN=1 129 | rust: beta 130 | # nightly 131 | - os: osx 132 | env: TARGET=i686-apple-darwin RUN=1 133 | rust: nightly 134 | # x86_64 135 | # stable 136 | - os: osx 137 | env: TARGET=x86_64-apple-darwin RUN=1 NO_ADD=1 138 | rust: stable 139 | # beta 140 | - os: osx 141 | env: TARGET=x86_64-apple-darwin RUN=1 NO_ADD=1 142 | rust: beta 143 | # nightly 144 | - os: osx 145 | env: TARGET=x86_64-apple-darwin RUN=1 NO_ADD=1 146 | rust: nightly 147 | # Android 148 | # i686 149 | # stable 150 | - env: TARGET=i686-linux-android 151 | rust: stable 152 | # beta 153 | - env: TARGET=i686-linux-android 154 | rust: beta 155 | # nightly 156 | - env: TARGET=i686-linux-android 157 | rust: nightly 158 | # x86_64 159 | # stable 160 | - env: TARGET=x86_64-linux-android 161 | rust: stable 162 | # beta 163 | - env: TARGET=x86_64-linux-android 164 | rust: beta 165 | # nightly 166 | - env: TARGET=x86_64-linux-android 167 | rust: nightly 168 | # arm 169 | # stable 170 | - env: TARGET=arm-linux-androideabi 171 | rust: stable 172 | # beta 173 | - env: TARGET=arm-linux-androideabi 174 | rust: beta 175 | # nightly 176 | - env: TARGET=arm-linux-androideabi 177 | rust: nightly 178 | # aarch64 179 | # stable 180 | - env: TARGET=aarch64-linux-android 181 | rust: stable 182 | # beta 183 | - env: TARGET=aarch64-linux-android 184 | rust: beta 185 | # nightly 186 | - env: TARGET=aarch64-linux-android 187 | rust: nightly 188 | 189 | 190 | script: 191 | - cargo build 192 | - cargo test 193 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate manages CPU affinities. 2 | //! 3 | //! ## Example 4 | //! 5 | //! This example shows how to create a thread for each available processor and pin each thread to its corresponding processor. 6 | //! 7 | //! ``` 8 | //! extern crate core_affinity; 9 | //! 10 | //! use std::thread; 11 | //! 12 | //! // Retrieve the IDs of all active CPU cores. 13 | //! let core_ids = core_affinity::get_core_ids().unwrap(); 14 | //! 15 | //! // Create a thread for each active CPU core. 16 | //! let handles = core_ids.into_iter().map(|id| { 17 | //! thread::spawn(move || { 18 | //! // Pin this thread to a single CPU core. 19 | //! let res = core_affinity::set_for_current(id); 20 | //! if (res) { 21 | //! // Do more work after this. 22 | //! } 23 | //! }) 24 | //! }).collect::>(); 25 | //! 26 | //! for handle in handles.into_iter() { 27 | //! handle.join().unwrap(); 28 | //! } 29 | //! ``` 30 | 31 | #[cfg(any( 32 | target_os = "android", 33 | target_os = "linux", 34 | target_os = "macos", 35 | target_os = "freebsd", 36 | target_os = "netbsd" 37 | ))] 38 | extern crate libc; 39 | 40 | #[cfg_attr(all(not(test), not(target_os = "macos")), allow(unused_extern_crates))] 41 | extern crate num_cpus; 42 | 43 | /// This function tries to retrieve information 44 | /// on all the "cores" on which the current thread 45 | /// is allowed to run. 46 | pub fn get_core_ids() -> Option> { 47 | get_core_ids_helper() 48 | } 49 | 50 | /// This function tries to pin the current 51 | /// thread to the specified core. 52 | /// 53 | /// # Arguments 54 | /// 55 | /// * core_id - ID of the core to pin 56 | pub fn set_for_current(core_id: CoreId) -> bool { 57 | set_for_current_helper(core_id) 58 | } 59 | 60 | /// This represents a CPU core. 61 | #[repr(transparent)] 62 | #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 63 | pub struct CoreId { 64 | pub id: usize, 65 | } 66 | 67 | // Linux Section 68 | 69 | #[cfg(any(target_os = "android", target_os = "linux"))] 70 | #[inline] 71 | fn get_core_ids_helper() -> Option> { 72 | linux::get_core_ids() 73 | } 74 | 75 | #[cfg(any(target_os = "android", target_os = "linux"))] 76 | #[inline] 77 | fn set_for_current_helper(core_id: CoreId) -> bool { 78 | linux::set_for_current(core_id) 79 | } 80 | 81 | #[cfg(any(target_os = "android", target_os = "linux"))] 82 | mod linux { 83 | use std::mem; 84 | 85 | use libc::{CPU_ISSET, CPU_SET, CPU_SETSIZE, cpu_set_t, sched_getaffinity, sched_setaffinity}; 86 | 87 | use super::CoreId; 88 | 89 | pub fn get_core_ids() -> Option> { 90 | if let Some(full_set) = get_affinity_mask() { 91 | let mut core_ids: Vec = Vec::new(); 92 | 93 | for i in 0..CPU_SETSIZE as usize { 94 | if unsafe { CPU_ISSET(i, &full_set) } { 95 | core_ids.push(CoreId{ id: i }); 96 | } 97 | } 98 | 99 | Some(core_ids) 100 | } 101 | else { 102 | None 103 | } 104 | } 105 | 106 | pub fn set_for_current(core_id: CoreId) -> bool { 107 | // Turn `core_id` into a `libc::cpu_set_t` with only 108 | // one core active. 109 | let mut set = new_cpu_set(); 110 | 111 | unsafe { CPU_SET(core_id.id, &mut set) }; 112 | 113 | // Set the current thread's core affinity. 114 | let res = unsafe { 115 | sched_setaffinity(0, // Defaults to current thread 116 | mem::size_of::(), 117 | &set) 118 | }; 119 | res == 0 120 | } 121 | 122 | fn get_affinity_mask() -> Option { 123 | let mut set = new_cpu_set(); 124 | 125 | // Try to get current core affinity mask. 126 | let result = unsafe { 127 | sched_getaffinity(0, // Defaults to current thread 128 | mem::size_of::(), 129 | &mut set) 130 | }; 131 | 132 | if result == 0 { 133 | Some(set) 134 | } 135 | else { 136 | None 137 | } 138 | } 139 | 140 | fn new_cpu_set() -> cpu_set_t { 141 | unsafe { mem::zeroed::() } 142 | } 143 | 144 | #[cfg(test)] 145 | mod tests { 146 | use num_cpus; 147 | 148 | use super::*; 149 | 150 | #[test] 151 | fn test_linux_get_affinity_mask() { 152 | match get_affinity_mask() { 153 | Some(_) => {}, 154 | None => { assert!(false); }, 155 | } 156 | } 157 | 158 | #[test] 159 | fn test_linux_get_core_ids() { 160 | match get_core_ids() { 161 | Some(set) => { 162 | assert_eq!(set.len(), num_cpus::get()); 163 | }, 164 | None => { assert!(false); }, 165 | } 166 | } 167 | 168 | #[test] 169 | fn test_linux_set_for_current() { 170 | let ids = get_core_ids().unwrap(); 171 | 172 | assert!(ids.len() > 0); 173 | 174 | let res = set_for_current(ids[0]); 175 | assert_eq!(res, true); 176 | 177 | // Ensure that the system pinned the current thread 178 | // to the specified core. 179 | let mut core_mask = new_cpu_set(); 180 | unsafe { CPU_SET(ids[0].id, &mut core_mask) }; 181 | 182 | let new_mask = get_affinity_mask().unwrap(); 183 | 184 | let mut is_equal = true; 185 | 186 | for i in 0..CPU_SETSIZE as usize { 187 | let is_set1 = unsafe { 188 | CPU_ISSET(i, &core_mask) 189 | }; 190 | let is_set2 = unsafe { 191 | CPU_ISSET(i, &new_mask) 192 | }; 193 | 194 | if is_set1 != is_set2 { 195 | is_equal = false; 196 | } 197 | } 198 | 199 | assert!(is_equal); 200 | } 201 | } 202 | } 203 | 204 | // Windows Section 205 | 206 | #[cfg(target_os = "windows")] 207 | #[inline] 208 | fn get_core_ids_helper() -> Option> { 209 | windows::get_core_ids() 210 | } 211 | 212 | #[cfg(target_os = "windows")] 213 | #[inline] 214 | fn set_for_current_helper(core_id: CoreId) -> bool { 215 | windows::set_for_current(core_id) 216 | } 217 | 218 | #[cfg(target_os = "windows")] 219 | extern crate winapi; 220 | 221 | #[cfg(target_os = "windows")] 222 | mod windows { 223 | use winapi::shared::basetsd::{DWORD_PTR, PDWORD_PTR}; 224 | use winapi::um::processthreadsapi::{GetCurrentProcess, GetCurrentThread}; 225 | use winapi::um::winbase::{GetProcessAffinityMask, SetThreadAffinityMask}; 226 | 227 | use super::CoreId; 228 | 229 | pub fn get_core_ids() -> Option> { 230 | if let Some(mask) = get_affinity_mask() { 231 | // Find all active cores in the bitmask. 232 | let mut core_ids: Vec = Vec::new(); 233 | 234 | for i in 0..64 as u64 { 235 | let test_mask = 1 << i; 236 | 237 | if (mask & test_mask) == test_mask { 238 | core_ids.push(CoreId { id: i as usize }); 239 | } 240 | } 241 | 242 | Some(core_ids) 243 | } 244 | else { 245 | None 246 | } 247 | } 248 | 249 | pub fn set_for_current(core_id: CoreId) -> bool { 250 | // Convert `CoreId` back into mask. 251 | let mask: u64 = 1 << core_id.id; 252 | 253 | // Set core affinity for current thread. 254 | let res = unsafe { 255 | SetThreadAffinityMask( 256 | GetCurrentThread(), 257 | mask as DWORD_PTR 258 | ) 259 | }; 260 | res != 0 261 | } 262 | 263 | fn get_affinity_mask() -> Option { 264 | let mut system_mask: usize = 0; 265 | let mut process_mask: usize = 0; 266 | 267 | let res = unsafe { 268 | GetProcessAffinityMask( 269 | GetCurrentProcess(), 270 | &mut process_mask as PDWORD_PTR, 271 | &mut system_mask as PDWORD_PTR 272 | ) 273 | }; 274 | 275 | // Successfully retrieved affinity mask 276 | if res != 0 { 277 | Some(process_mask as u64) 278 | } 279 | // Failed to retrieve affinity mask 280 | else { 281 | None 282 | } 283 | } 284 | 285 | #[cfg(test)] 286 | mod tests { 287 | use num_cpus; 288 | 289 | use super::*; 290 | 291 | #[test] 292 | fn test_windows_get_core_ids() { 293 | match get_core_ids() { 294 | Some(set) => { 295 | assert_eq!(set.len(), num_cpus::get()); 296 | }, 297 | None => { assert!(false); }, 298 | } 299 | } 300 | 301 | #[test] 302 | fn test_windows_set_for_current() { 303 | let ids = get_core_ids().unwrap(); 304 | 305 | assert!(ids.len() > 0); 306 | 307 | assert_ne!(set_for_current(ids[0]), 0); 308 | } 309 | } 310 | } 311 | 312 | // MacOS Section 313 | 314 | #[cfg(target_os = "macos")] 315 | #[inline] 316 | fn get_core_ids_helper() -> Option> { 317 | macos::get_core_ids() 318 | } 319 | 320 | #[cfg(target_os = "macos")] 321 | #[inline] 322 | fn set_for_current_helper(core_id: CoreId) -> bool { 323 | macos::set_for_current(core_id) 324 | } 325 | 326 | #[cfg(target_os = "macos")] 327 | mod macos { 328 | use std::mem; 329 | 330 | use libc::{c_int, c_uint, c_void, pthread_self}; 331 | 332 | use num_cpus; 333 | 334 | use super::CoreId; 335 | 336 | type kern_return_t = c_int; 337 | type integer_t = c_int; 338 | type natural_t = c_uint; 339 | type thread_t = c_uint; 340 | type thread_policy_flavor_t = natural_t; 341 | type mach_msg_type_number_t = natural_t; 342 | 343 | #[repr(C)] 344 | struct thread_affinity_policy_data_t { 345 | affinity_tag: integer_t, 346 | } 347 | 348 | type thread_policy_t = *mut thread_affinity_policy_data_t; 349 | 350 | const THREAD_AFFINITY_POLICY: thread_policy_flavor_t = 4; 351 | 352 | extern { 353 | fn thread_policy_set( 354 | thread: thread_t, 355 | flavor: thread_policy_flavor_t, 356 | policy_info: thread_policy_t, 357 | count: mach_msg_type_number_t, 358 | ) -> kern_return_t; 359 | } 360 | 361 | pub fn get_core_ids() -> Option> { 362 | Some((0..(num_cpus::get())).into_iter() 363 | .map(|n| CoreId { id: n as usize }) 364 | .collect::>()) 365 | } 366 | 367 | pub fn set_for_current(core_id: CoreId) -> bool { 368 | let THREAD_AFFINITY_POLICY_COUNT: mach_msg_type_number_t = 369 | mem::size_of::() as mach_msg_type_number_t / 370 | mem::size_of::() as mach_msg_type_number_t; 371 | 372 | let mut info = thread_affinity_policy_data_t { 373 | affinity_tag: core_id.id as integer_t, 374 | }; 375 | 376 | let res = unsafe { 377 | thread_policy_set( 378 | pthread_self() as thread_t, 379 | THREAD_AFFINITY_POLICY, 380 | &mut info as thread_policy_t, 381 | THREAD_AFFINITY_POLICY_COUNT 382 | ) 383 | }; 384 | res == 0 385 | } 386 | 387 | #[cfg(test)] 388 | mod tests { 389 | use num_cpus; 390 | 391 | use super::*; 392 | 393 | #[test] 394 | fn test_macos_get_core_ids() { 395 | match get_core_ids() { 396 | Some(set) => { 397 | assert_eq!(set.len(), num_cpus::get()); 398 | }, 399 | None => { assert!(false); }, 400 | } 401 | } 402 | 403 | #[test] 404 | fn test_macos_set_for_current() { 405 | let ids = get_core_ids().unwrap(); 406 | assert!(ids.len() > 0); 407 | assert!(set_for_current(ids[0])) 408 | } 409 | } 410 | } 411 | 412 | 413 | // FreeBSD Section 414 | 415 | #[cfg(target_os = "freebsd")] 416 | #[inline] 417 | fn get_core_ids_helper() -> Option> { 418 | freebsd::get_core_ids() 419 | } 420 | 421 | #[cfg(target_os = "freebsd")] 422 | #[inline] 423 | fn set_for_current_helper(core_id: CoreId) -> bool { 424 | freebsd::set_for_current(core_id) 425 | } 426 | 427 | #[cfg(target_os = "freebsd")] 428 | mod freebsd { 429 | use std::mem; 430 | 431 | use libc::{ 432 | cpuset_getaffinity, cpuset_setaffinity, cpuset_t, CPU_ISSET, 433 | CPU_LEVEL_WHICH, CPU_SET, CPU_SETSIZE, CPU_WHICH_TID, 434 | }; 435 | 436 | use super::CoreId; 437 | 438 | pub fn get_core_ids() -> Option> { 439 | if let Some(full_set) = get_affinity_mask() { 440 | let mut core_ids: Vec = Vec::new(); 441 | 442 | for i in 0..CPU_SETSIZE as usize { 443 | if unsafe { CPU_ISSET(i, &full_set) } { 444 | core_ids.push(CoreId { id: i }); 445 | } 446 | } 447 | 448 | Some(core_ids) 449 | } else { 450 | None 451 | } 452 | } 453 | 454 | pub fn set_for_current(core_id: CoreId) -> bool { 455 | // Turn `core_id` into a `libc::cpuset_t` with only 456 | // one core active. 457 | let mut set = new_cpu_set(); 458 | 459 | unsafe { CPU_SET(core_id.id, &mut set) }; 460 | 461 | // Set the current thread's core affinity. 462 | let res = unsafe { 463 | // FreeBSD's sched_setaffinity currently operates on process id, 464 | // therefore using cpuset_setaffinity instead. 465 | cpuset_setaffinity( 466 | CPU_LEVEL_WHICH, 467 | CPU_WHICH_TID, 468 | -1, // -1 == current thread 469 | mem::size_of::(), 470 | &set, 471 | ) 472 | }; 473 | res == 0 474 | } 475 | 476 | fn get_affinity_mask() -> Option { 477 | let mut set = new_cpu_set(); 478 | 479 | // Try to get current core affinity mask. 480 | let result = unsafe { 481 | // FreeBSD's sched_getaffinity currently operates on process id, 482 | // therefore using cpuset_getaffinity instead. 483 | cpuset_getaffinity( 484 | CPU_LEVEL_WHICH, 485 | CPU_WHICH_TID, 486 | -1, // -1 == current thread 487 | mem::size_of::(), 488 | &mut set, 489 | ) 490 | }; 491 | 492 | if result == 0 { 493 | Some(set) 494 | } else { 495 | None 496 | } 497 | } 498 | 499 | fn new_cpu_set() -> cpuset_t { 500 | unsafe { mem::zeroed::() } 501 | } 502 | 503 | #[cfg(test)] 504 | mod tests { 505 | use num_cpus; 506 | 507 | use super::*; 508 | 509 | #[test] 510 | fn test_freebsd_get_affinity_mask() { 511 | match get_affinity_mask() { 512 | Some(_) => {} 513 | None => { 514 | assert!(false); 515 | } 516 | } 517 | } 518 | 519 | #[test] 520 | fn test_freebsd_get_core_ids() { 521 | match get_core_ids() { 522 | Some(set) => { 523 | assert_eq!(set.len(), num_cpus::get()); 524 | } 525 | None => { 526 | assert!(false); 527 | } 528 | } 529 | } 530 | 531 | #[test] 532 | fn test_freebsd_set_for_current() { 533 | let ids = get_core_ids().unwrap(); 534 | 535 | assert!(ids.len() > 0); 536 | 537 | let res = set_for_current(ids[0]); 538 | assert_eq!(res, true); 539 | 540 | // Ensure that the system pinned the current thread 541 | // to the specified core. 542 | let mut core_mask = new_cpu_set(); 543 | unsafe { CPU_SET(ids[0].id, &mut core_mask) }; 544 | 545 | let new_mask = get_affinity_mask().unwrap(); 546 | 547 | let mut is_equal = true; 548 | 549 | for i in 0..CPU_SETSIZE as usize { 550 | let is_set1 = unsafe { CPU_ISSET(i, &core_mask) }; 551 | let is_set2 = unsafe { CPU_ISSET(i, &new_mask) }; 552 | 553 | if is_set1 != is_set2 { 554 | is_equal = false; 555 | } 556 | } 557 | 558 | assert!(is_equal); 559 | } 560 | } 561 | } 562 | 563 | // NetBSD Section 564 | 565 | #[cfg(target_os = "netbsd")] 566 | #[inline] 567 | fn get_core_ids_helper() -> Option> { 568 | netbsd::get_core_ids() 569 | } 570 | 571 | #[cfg(target_os = "netbsd")] 572 | #[inline] 573 | fn set_for_current_helper(core_id: CoreId) -> bool { 574 | netbsd::set_for_current(core_id) 575 | } 576 | 577 | #[cfg(target_os = "netbsd")] 578 | mod netbsd { 579 | use libc::{ 580 | pthread_getaffinity_np, pthread_setaffinity_np, pthread_self, cpuset_t, 581 | _cpuset_create, _cpuset_size, _cpuset_set, _cpuset_isset, _cpuset_destroy 582 | }; 583 | use num_cpus; 584 | 585 | use super::CoreId; 586 | 587 | pub fn get_core_ids() -> Option> { 588 | if let Some(full_set) = get_affinity_mask() { 589 | let mut core_ids: Vec = Vec::new(); 590 | 591 | let num_cpus = num_cpus::get(); 592 | for i in 0..num_cpus { 593 | if unsafe { _cpuset_isset(i as u64, full_set) } >= 0 { 594 | core_ids.push(CoreId { id: i }); 595 | } 596 | } 597 | unsafe { _cpuset_destroy(full_set) }; 598 | Some(core_ids) 599 | } else { 600 | None 601 | } 602 | } 603 | 604 | pub fn set_for_current(core_id: CoreId) -> bool { 605 | let set = unsafe { _cpuset_create() }; 606 | unsafe { _cpuset_set(core_id.id as u64, set) } ; 607 | 608 | let result = unsafe { 609 | pthread_setaffinity_np(pthread_self(), _cpuset_size(set), set) 610 | }; 611 | unsafe { _cpuset_destroy(set) }; 612 | 613 | match result { 614 | 0 => true, 615 | _ => false, 616 | } 617 | } 618 | 619 | fn get_affinity_mask() -> Option<*mut cpuset_t> { 620 | let set = unsafe { _cpuset_create() }; 621 | 622 | match unsafe { 623 | pthread_getaffinity_np(pthread_self(), _cpuset_size(set), set) 624 | } { 625 | 0 => Some(set), 626 | _ => None, 627 | } 628 | } 629 | 630 | #[cfg(test)] 631 | mod tests { 632 | use num_cpus; 633 | 634 | use super::*; 635 | 636 | #[test] 637 | fn test_netbsd_get_affinity_mask() { 638 | match get_affinity_mask() { 639 | Some(set) => unsafe { _cpuset_destroy(set); }, 640 | None => { 641 | assert!(false); 642 | } 643 | } 644 | } 645 | 646 | #[test] 647 | fn test_netbsd_get_core_ids() { 648 | match get_core_ids() { 649 | Some(set) => { 650 | assert_eq!(set.len(), num_cpus::get()); 651 | } 652 | None => { 653 | assert!(false); 654 | } 655 | } 656 | } 657 | 658 | #[test] 659 | fn test_netbsd_set_for_current() { 660 | let ids = get_core_ids().unwrap(); 661 | 662 | assert!(ids.len() > 0); 663 | 664 | let ci = ids[ids.len() - 1]; // use the last reported core 665 | let res = set_for_current(ci); 666 | assert_eq!(res, true); 667 | 668 | // Ensure that the system pinned the current thread 669 | // to the specified core. 670 | let new_mask = get_affinity_mask().unwrap(); 671 | assert!(unsafe { _cpuset_isset(ci.id as u64, new_mask) > 0 }); 672 | let num_cpus = num_cpus::get(); 673 | for i in 0..num_cpus { 674 | if i != ci.id { 675 | assert_eq!(0, unsafe { _cpuset_isset(i as u64, new_mask) }); 676 | } 677 | } 678 | unsafe { _cpuset_destroy(new_mask) }; 679 | } 680 | } 681 | } 682 | 683 | // Stub Section 684 | 685 | #[cfg(not(any( 686 | target_os = "linux", 687 | target_os = "android", 688 | target_os = "windows", 689 | target_os = "macos", 690 | target_os = "freebsd", 691 | target_os = "netbsd" 692 | )))] 693 | #[inline] 694 | fn get_core_ids_helper() -> Option> { 695 | None 696 | } 697 | 698 | #[cfg(not(any( 699 | target_os = "linux", 700 | target_os = "android", 701 | target_os = "windows", 702 | target_os = "macos", 703 | target_os = "freebsd", 704 | target_os = "netbsd" 705 | )))] 706 | #[inline] 707 | fn set_for_current_helper(_core_id: CoreId) -> bool { 708 | false 709 | } 710 | 711 | #[cfg(test)] 712 | mod tests { 713 | use num_cpus; 714 | 715 | use super::*; 716 | 717 | // #[test] 718 | // fn test_num_cpus() { 719 | // println!("Num CPUs: {}", num_cpus::get()); 720 | // println!("Num Physical CPUs: {}", num_cpus::get_physical()); 721 | // } 722 | 723 | #[test] 724 | fn test_get_core_ids() { 725 | match get_core_ids() { 726 | Some(set) => { 727 | assert_eq!(set.len(), num_cpus::get()); 728 | }, 729 | None => { assert!(false); }, 730 | } 731 | } 732 | 733 | #[test] 734 | fn test_set_for_current() { 735 | let ids = get_core_ids().unwrap(); 736 | assert!(ids.len() > 0); 737 | assert!(set_for_current(ids[0])) 738 | } 739 | } 740 | --------------------------------------------------------------------------------