blob: 490c66148685cf563a1fee84c4bdd1c978caae5a (
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
71
72
73
74
75
76
|
// SPDX-License-Identifier: GPL-3.0-or-later
/*
* A very simple pthreads program to spawn N busy threads.
* It is just used for validating apps.plugin CPU utilization
* calculations per operating system.
*
* Compile with:
*
* gcc -O2 -ggdb -o busy_threads busy_threads.c -pthread
*
* Run as:
*
* busy_threads 2
*
* The above will create 2 busy threads, each using 1 core in user time.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
volatile int keep_running = 1;
void handle_signal(int signal) {
keep_running = 0;
}
void *busy_loop(void *arg) {
while (keep_running) {
// Busy loop to keep CPU at 100%
}
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
exit(EXIT_FAILURE);
}
int num_threads = atoi(argv[1]);
if (num_threads <= 0) {
fprintf(stderr, "Number of threads must be a positive integer.\n");
exit(EXIT_FAILURE);
}
// Register the signal handler to gracefully exit on Ctrl-C
signal(SIGINT, handle_signal);
pthread_t *threads = malloc(sizeof(pthread_t) * num_threads);
if (threads == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
// Create threads
for (int i = 0; i < num_threads; i++) {
if (pthread_create(&threads[i], NULL, busy_loop, NULL) != 0) {
perror("pthread_create");
free(threads);
exit(EXIT_FAILURE);
}
}
// Wait for threads to finish (they never will unless interrupted)
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
free(threads);
return 0;
}
|