8 /* Load function for threads. */
9 static void* produce(void* arg);
10 static void* consume(void* arg);
12 /* semaphores for consumer/producer pair */
13 static sem_t produced, consumed;
14 /* pthread handles for the loader */
15 static pthread_t consumer, producer;
17 static char running = 0;
19 static void* produce(void* arg){
29 static void* consume(void* arg){
40 * This function starts threads loading the CPU and creates associated semaphores.
42 * Has a guard to prevent starting again, before it was stopped.
44 * No error handling currently, only tries to report errors.
46 int start_thread_load(){
48 printf("Attempting to start load.\n");
51 res = sem_init(&consumed, 0, 0);
53 printf("Couldn't initialize consumed semaphore.\n");
56 res = sem_init(&produced, 0, 1);
58 printf("Couldn't initialize produced semaphore.\n");
62 res = pthread_create(&producer, NULL, produce, NULL);
64 printf("Couldn't create producer thread.\n");
68 res = pthread_create(&consumer, NULL, consume, NULL);
70 printf("Couldn't create consumer thread.\n");
74 pthread_detach(producer);
75 pthread_detach(consumer);
76 printf("Load started succesfully.\n");
79 printf("Load is already running.\n");
85 * This function stops threads loading the CPU and destroys associated semaphores.
87 * Has a guard against attempting to stop the threads if they are not running.
89 * No error handling currently, only tries to report errors.
91 int end_thread_load(){
94 printf("Attempting to cancel producer thread.\n");
95 res = pthread_cancel(producer);
97 /* This means that sending cancel signal has failed... Just returning an error should be enough. */
98 /* If we killed the thread, destroying the semaphore would lead to UB. */
103 printf("Attempting to cancel consumer thread.\n");
104 res = pthread_cancel(consumer);
111 printf("Preparing to destroy semaphores.\n");
112 /* Wait a bit so that the threads can get to a cancellation point. */
114 sem_destroy(&produced);
115 sem_destroy(&consumed);
117 printf("Finished.\n");
120 printf("Load is not running.\n");