I am benchmarking against an annoying piece of cpp program on linux. The program is a mess and complicated as hell! It automatically does multi-threading, and I wonder if there is any way to force by calling it via something, i.e. taskset, etc to use only 1 thread.
Edit: I have tried setting "taskset 01 program arg1 ..." but it doesn't work. I just saw the program using 100 threads!
To limit a Linux process to run on one core use taskset. The following is taken from https://serverfault.com/a/32331
taskset <affinity mask> -p <process>
i.e.
taskset 1 -p 12345
to set process 12345 to use only processor/core 1
The bitmask can be a list (i.e. 1,3,4 to use cores 1 3 and 4 of a 4+ core system) or a bitmask in hex (0x0000000D the 1,3,4, 0x00000001 for just core 1)
taskset is usually in a package called shedutils.
Edit: almost forgot... If you want to set the affinity of a new command instead of change it for an existing process, use:
taskset <mask> <program> [<arg1>]...[<argN>]
(I assume you accept a Linux specific solution)
On Linux, threads (at least NPTL ones) are created using the clone(2) syscall. It is documented to fail with
EAGAINToo many processes are already running; see fork(2).
(In fact, the kernel is scheduling tasks which may be threads or [single-threaded] processes)
You could use setrlimit(2) with RLIMIT_NPROC:
RLIMIT_NPROCThe maximum number of processes (or, more precisely on Linux, threads) that can be created for the real user ID of the calling process.
So I guess that you might use that (perhaps with the ulimit bash builtin in the shell running in your terminal) to limit the number of successfully created threads (actually "tasks").
But I am not sure it would be a good idea. A well written program would test against failure of pthread_create(3) (which is internally calling clone(2)). A poorly written program would crash.
Maybe that program is using some thread pool and there is some way to limit the size of that pool. BTW, you can run dozens of threads on only two cores -or even a single core- (especially when most of the time the threads are idle, e.g. poll(2)-ing or waiting for I/O).
PS. For benchmarking purposes, you probably should care more about limiting the number of cores (with taskset) than limiting the number of threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With