| 1 |
<!-- |
| 2 |
%\VignetteIndexEntry{Parallel Workers on the Local Machine} |
| 3 |
%\VignetteAuthor{Henrik Bengtsson} |
| 4 |
%\VignetteKeyword{R} |
| 5 |
%\VignetteKeyword{package} |
| 6 |
%\VignetteKeyword{vignette} |
| 7 |
%\VignetteEngine{parallelly::selfonly} |
| 8 |
--> |
| 9 |
|
| 10 |
|
| 11 |
# Introduction |
| 12 |
|
| 13 |
This vignette illustrates how to launch parallel workers on the |
| 14 |
current, local machine. This works the same on all operating systems |
| 15 |
where R is supported, e.g. Linux, macOS, and MS Windows. |
| 16 |
|
| 17 |
|
| 18 |
# Examples |
| 19 |
|
| 20 |
## Example: Launching two parallel workers |
| 21 |
|
| 22 |
The below illustrates how to launch a cluster of two parallel workers |
| 23 |
on the current machine, run some basic calculations in parallel, and |
| 24 |
then shut down the cluster. |
| 25 |
|
| 26 |
```r |
| 27 |
library(parallelly) |
| 28 |
library(parallel) |
| 29 |
|
| 30 |
cl <- makeClusterPSOCK(2) |
| 31 |
print(cl) |
| 32 |
#> Socket cluster with 2 nodes on host 'localhost' (R version 4.5.2 |
| 33 |
#> (2025-10-31), platform x86_64-pc-linux-gnu) |
| 34 |
|
| 35 |
y <- parLapply(cl, X = 1:100, fun = sqrt) |
| 36 |
y <- unlist(y) |
| 37 |
z <- sum(y) |
| 38 |
print(z) |
| 39 |
#> [1] 671.4629 |
| 40 |
|
| 41 |
parallel::stopCluster(cl) |
| 42 |
``` |
| 43 |
|
| 44 |
_Comment_: In the **parallel** package, a parallel worker is referred |
| 45 |
to a parallel node, or short _node_, which is why we use the same term |
| 46 |
in the **parallelly** package. |
| 47 |
|
| 48 |
|
| 49 |
An alternative to specifying the _number_ of parallel workers is to |
| 50 |
specify a character vector with that number of `"localhost"` entries, |
| 51 |
e.g. |
| 52 |
|
| 53 |
```r |
| 54 |
cl <- makeClusterPSOCK(c("localhost", "localhost")) |
| 55 |
``` |
| 56 |
|
| 57 |
|
| 58 |
## Example: Launching as many parallel workers as allotted |
| 59 |
|
| 60 |
The `availableCores()` function will return the number of workers that |
| 61 |
the system allows. It respects many common settings that control the |
| 62 |
number of CPU cores that the current R process is allotted, e.g. R |
| 63 |
options, environment variables, and CGroups settings. For details, see |
| 64 |
`help("availableCores")`. For example, |
| 65 |
|
| 66 |
```r |
| 67 |
library(parallelly) |
| 68 |
cl <- makeClusterPSOCK(availableCores()) |
| 69 |
print(cl) |
| 70 |
#> Socket cluster with 8 nodes on host 'localhost' (R version 4.5.2 |
| 71 |
#> (2025-10-31), platform x86_64-pc-linux-gnu) |
| 72 |
``` |