Created
November 30, 2025 20:33
-
-
Save rene-d/b9f1c0a908d8ec5bec929d5b41065426 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <pthread.h> | |
| #include <signal.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <sys/resource.h> | |
| #include <unistd.h> | |
| static volatile int running = 1; | |
| static void sig_handler(int sig __attribute__((unused))) | |
| { | |
| printf("[%p] stop\n", pthread_self()); | |
| running = 0; | |
| } | |
| static void *oqp(void *ptr __attribute__((unused))) | |
| { | |
| int policy; | |
| struct sched_param sched_param; | |
| int retcode; | |
| retcode = pthread_getschedparam(pthread_self(), &policy, &sched_param); | |
| if (retcode != 0) { | |
| perror("pthread_getschedparam"); | |
| } else { | |
| printf("[%p] policy=%d sched_prio=%d\n", pthread_self(), policy, sched_param.sched_priority); | |
| } | |
| while (1) { | |
| if (running == 0) { | |
| break; | |
| } | |
| } | |
| return NULL; | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| int nb_oqp = 4; | |
| const id_t current_process = 0; | |
| int prio; | |
| int retcode; | |
| pthread_t *thread_ids; | |
| if (argc > 1) { | |
| nb_oqp = atoi(argv[1]); | |
| } | |
| if (nb_oqp < 1 || nb_oqp > (int)sysconf(_SC_NPROCESSORS_ONLN)) { | |
| fprintf(stderr, "Error: nb_oqp must be between 1 and %ld\n", sysconf(_SC_NPROCESSORS_ONLN)); | |
| exit(EXIT_FAILURE); | |
| } | |
| prio = getpriority(PRIO_PROCESS, current_process); | |
| printf("[%p] old priority: %d\n", pthread_self(), prio); | |
| retcode = setpriority(PRIO_PROCESS, current_process, PRIO_DARWIN_BG); | |
| if (retcode != 0) { | |
| perror("setpriority"); | |
| } | |
| prio = getpriority(PRIO_PROCESS, current_process); | |
| printf("[%p] new priority: %d\n", pthread_self(), prio); | |
| signal(SIGINT, &sig_handler); | |
| signal(SIGQUIT, &sig_handler); | |
| signal(SIGTERM, &sig_handler); | |
| signal(SIGHUP, &sig_handler); | |
| thread_ids = (pthread_t *)malloc(sizeof(pthread_t) * (nb_oqp - 1)); | |
| for (int i = 0; i < nb_oqp - 1; ++i) { | |
| retcode = pthread_create(&thread_ids[i], NULL, &oqp, NULL); | |
| if (retcode != 0) { | |
| perror("pthread_create"); | |
| } else { | |
| printf("[%p] new thread %d: %p\n", pthread_self(), i, thread_ids[i]); | |
| } | |
| } | |
| oqp(NULL); | |
| for (int i = 0; i < nb_oqp - 1; ++i) { | |
| retcode = pthread_join(thread_ids[i], NULL); | |
| if (retcode != 0) { | |
| perror("pthread_join"); | |
| } | |
| printf("[%p] join thread %p\n", pthread_self(), thread_ids[i]); | |
| } | |
| free(thread_ids); | |
| printf("[%p] exit\n", pthread_self()); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment