2 * Implements simple producer/consumer thread pair to cause load on the CPU.
\r
4 * Used in benchmarking the CAN gateway.
\r
6 * Co-opted from http://support.dce.felk.cvut.cz/pos/cv3/src/semaphore.html.
\r
11 #include <pthread.h>
\r
12 #include <semaphore.h>
\r
17 static void* produce(void* arg);
\r
18 static void* consume(void* arg);
\r
20 /* semaphores for consumer/producer pair */
\r
21 static sem_t produced, consumed;
\r
22 /* pthread handles for the loader */
\r
23 static pthread_t consumer, producer;
\r
25 static char running = 0;
\r
27 static void* produce(void* arg){
\r
29 sem_wait(&consumed);
\r
30 n++; /* increment n by 1 */
\r
31 sem_post(&produced);
\r
32 pthread_testcancel();
\r
37 static void* consume(void* arg){
\r
39 sem_wait(&produced);
\r
40 n--; /* aaand decrement */
\r
41 sem_post(&consumed);
\r
42 pthread_testcancel();
\r
47 int start_thread_load(){
\r
49 printf("Attempting to start load.\n");
\r
52 res = sem_init(&consumed, 0, 0);
\r
54 printf("Couldn't initialize consumed semaphore.\n");
\r
57 res = sem_init(&produced, 0, 1);
\r
59 printf("Couldn't initialize produced semaphore.\n");
\r
63 res = pthread_create(&producer, NULL, produce, NULL);
\r
65 printf("Couldn't create producer thread.\n");
\r
69 res = pthread_create(&consumer, NULL, consume, NULL);
\r
71 printf("Couldn't create consumer thread.\n");
\r
75 pthread_detach(producer);
\r
76 pthread_detach(consumer);
\r
77 printf("Load started succesfully.\n");
\r
80 printf("Load is already running.\n");
\r
86 * This function stops threads loading the CPU and destroys associated semaphores.
\r
88 * 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 printf("Failed.\n");
\r
98 /* Not sure what to do with error here, will have to figure out later. */
\r
100 printf("Attempting to cancel consumer thread.\n");
\r
101 res = pthread_cancel(consumer);
\r
103 printf("Failed.\n");
\r
105 printf("Preparing to destroy semaphores.\n");
\r
107 sem_destroy(&produced);
\r
108 sem_destroy(&consumed);
\r
110 printf("Finished.\n");
\r
113 printf("Load is not running.\n");
\r