master
c 76 lines 1.72 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 /*
4 * A very simple pthreads program to spawn N busy threads.
5 * It is just used for validating apps.plugin CPU utilization
6 * calculations per operating system.
7 *
8 * Compile with:
9 *
10 * gcc -O2 -ggdb -o busy_threads busy_threads.c -pthread
11 *
12 * Run as:
13 *
14 * busy_threads 2
15 *
16 * The above will create 2 busy threads, each using 1 core in user time.
17 *
18 */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <pthread.h>
23 #include <signal.h>
24 #include <unistd.h>
25
26 volatile int keep_running = 1;
27
28 void handle_signal(int signal) {
29 keep_running = 0;
30 }
31
32 void *busy_loop(void *arg) {
33 while (keep_running) {
34 // Busy loop to keep CPU at 100%
35 }
36 return NULL;
37 }
38
39 int main(int argc, char *argv[]) {
40 if (argc != 2) {
41 fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
42 exit(EXIT_FAILURE);
43 }
44
45 int num_threads = atoi(argv[1]);
46 if (num_threads <= 0) {
47 fprintf(stderr, "Number of threads must be a positive integer.\n");
48 exit(EXIT_FAILURE);
49 }
50
51 // Register the signal handler to gracefully exit on Ctrl-C
52 signal(SIGINT, handle_signal);
53
54 pthread_t *threads = malloc(sizeof(pthread_t) * num_threads);
55 if (threads == NULL) {
56 perror("malloc");
57 exit(EXIT_FAILURE);
58 }
59
60 // Create threads
61 for (int i = 0; i < num_threads; i++) {
62 if (pthread_create(&threads[i], NULL, busy_loop, NULL) != 0) {
63 perror("pthread_create");
64 free(threads);
65 exit(EXIT_FAILURE);
66 }
67 }
68
69 // Wait for threads to finish (they never will unless interrupted)
70 for (int i = 0; i < num_threads; i++) {
71 pthread_join(threads[i], NULL);
72 }
73
74 free(threads);
75 return 0;
76 }