-/*\r
-* Implements simple producer/consumer thread pair to cause load on the CPU.\r
-* \r
-* Used in benchmarking the CAN gateway.\r
-*\r
-* Co-opted from http://support.dce.felk.cvut.cz/pos/cv3/src/semaphore.html. \r
-*/\r
-\r
#include <stdio.h>\r
\r
#include <pthread.h>\r
\r
#include "load.h"\r
\r
-\r
+/* Load function for threads. */\r
static void* produce(void* arg);\r
static void* consume(void* arg);\r
\r
static void* produce(void* arg){\r
while (1) {\r
sem_wait(&consumed);\r
- n++; /* increment n by 1 */\r
+ n++; \r
sem_post(&produced);\r
pthread_testcancel();\r
}\r
static void* consume(void* arg){\r
while (1) {\r
sem_wait(&produced);\r
- n--; /* aaand decrement */\r
+ n--;\r
sem_post(&consumed);\r
pthread_testcancel();\r
}\r
return NULL;\r
}\r
\r
+/*\r
+* This function starts threads loading the CPU and creates associated semaphores. \r
+* \r
+* Has a guard to prevent starting again, before it was stopped.\r
+*\r
+* No error handling currently, only tries to report errors.\r
+*/\r
int start_thread_load(){\r
if (running == 0){\r
printf("Attempting to start load.\n");\r
\r
/*\r
* This function stops threads loading the CPU and destroys associated semaphores. \r
+*\r
+* Has a guard against attempting to stop the threads if they are not running.\r
* \r
* No error handling currently, only tries to report errors.\r
-* \r
*/\r
int end_thread_load(){\r
if (running == 1){\r
printf("Attempting to cancel producer thread.\n");\r
res = pthread_cancel(producer);\r
if (res != 0){\r
+ /* This means that sending cancel signal has failed... Just returning an error should be enough. */\r
+ /* If we killed the thread, destroying the semaphore would lead to UB. */\r
printf("Failed.\n");\r
- /* Not sure what to do with error here, will have to figure out later. */\r
+ return 1;\r
}\r
+\r
printf("Attempting to cancel consumer thread.\n");\r
res = pthread_cancel(consumer);\r
if (res != 0){\r
+ /* Same here. */\r
printf("Failed.\n");\r
+ return 1;\r
}\r
+\r
printf("Preparing to destroy semaphores.\n");\r
+ /* Wait a bit so that the threads can get to a cancellation point. */\r
sleep(1);\r
sem_destroy(&produced);\r
sem_destroy(&consumed);\r