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