๐Ÿ“ฆ justjavac / moonbit-core-affinity

๐Ÿ“„ README.md ยท 111 lines
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111# moonbit-core-affinity

A MoonBit library for managing CPU core affinities to control thread-to-core binding.

This library enables precise control over CPU core affinity, allowing you to bind threads to specific cores. It's particularly useful for high-performance applications, real-time systems, and scenarios where you need to optimize CPU cache locality, reduce context switching overhead, or isolate workloads on dedicated cores.

## Installation

Add `justjavac/core_affinity` to your dependencies:

```bash
moon update
moon add justjavac/core_affinity
```

## Usage

```moonbit
fn main {
  // Get available core IDs
  let core_ids = @core_affinity.get_core_ids()
  println("Available core IDs: \{core_ids}")
  
  // Early return if no cores are available
  if core_ids.length() == 0 {
    println("No available cores found.")
    return
  }
  
  let first_core_id = core_ids[0]
  println("Setting affinity to core: \{first_core_id}")
  
  let success = @core_affinity.set_for_current([first_core_id])
  if not(success) {
    println("Failed to set affinity to core: \{first_core_id}")
    return
  }

  println("Successfully set affinity to core: \{first_core_id}")
}
```

## Platform Support

| Platform | get_core_ids() | set_for_current() | Implementation |
|----------|----------------|-------------------|----------------|
| Windows | โœ… | โœ… | Win32 API (`GetProcessAffinityMask`, `SetThreadAffinityMask`) |
| Linux | โœ… | โœ… | POSIX (`sched_getaffinity`, `sched_setaffinity`) |
| macOS | โœ… | โœ… | BSD/Darwin thread affinity APIs |
| Other Unix | โš ๏ธ | โš ๏ธ | Limited support, platform-dependent |

- โœ… = Full support
- โš ๏ธ = Limited/platform-dependent support

## Examples

### Basic Usage

```moonbit
fn main {
  let cores = @core_affinity.get_core_ids()
  println("Available cores: \{cores}")
}
```

### Single Core Binding

```moonbit
fn bind_to_first_core() -> Bool {
  let cores = @core_affinity.get_core_ids()
  if cores.length() > 0 {
    @core_affinity.set_for_current([cores[0]])
  } else {
    false
  }
}
```

### Multi-Core Binding

```moonbit
fn bind_to_even_cores() -> Bool {
  let cores = @core_affinity.get_core_ids()
  let even_cores = []
  
  for core in cores {
    if core % 2 == 0 {
      even_cores.push(core)
    }
  }
  
  if even_cores.length() > 0 {
    @core_affinity.set_for_current(even_cores)
  } else {
    false
  }
}
```

## Examples

You can find example usage in the `example/` directory:

```bash
moon run --target native -C example .
```

## License

MIT License - see [LICENSE](LICENSE) file for details.