Skip to content

Commit

Permalink
Fixed thread example
Browse files Browse the repository at this point in the history
  • Loading branch information
BDeliers committed Sep 1, 2023
1 parent 97a17e0 commit 82f6063
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
24 changes: 15 additions & 9 deletions samples/threading/main.c
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#include "log.h"
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

static bool s_stop = false;
pthread_mutex_t MUTEX_LOG;

void log_lock(bool lock, void *mutex);

// Mutex lock function for log module
void log_lock(bool lock, void* mutex) {
pthread_mutex_t *LOCK = (pthread_mutex_t*)(mutex);

Expand All @@ -20,7 +20,8 @@ void log_lock(bool lock, void* mutex) {
}
}

void run(void *arg) {
// Thread runner function
void* run(void *arg) {
// Retrieve this thread's id
int id = *(int*)arg;

Expand All @@ -37,8 +38,11 @@ void run(void *arg) {

if (s_stop) { break; }
}

return 0;
}

// Signal catcher
void stop(int signo) {
(void)signo;
s_stop = true;
Expand All @@ -53,30 +57,32 @@ int main() {

FILE* fp = fopen ("./demo.log", "a+");

log_set_level(LOG_DEBUG);
log_add_fp(fp, LOG_DEBUG);
log_set_level(LOGC_DEBUG);
log_add_fp(fp, LOGC_DEBUG);

// Redirect signals to stop() fucntion
signal(SIGINT, stop);
signal(SIGKILL, stop);
signal(SIGTERM, stop);

pthread_t h[8];
pthread_t thread_handles[8];
int id_array[8] = {0,1,2,3,4,5,6,7};

// Create 8 threads, each passing their id as parameter
for (int i= 0; i<8; i++) {
pthread_create(&h[i], NULL, run, &id_array[i]);
pthread_create(&thread_handles[i], NULL, run, &id_array[i]);
}

void* ret[8] = {NULL};
void* thread_retvals[8] = {NULL};

// Start threads
for (int i=0; i<8; i++) {
pthread_join(h[i], &ret);
pthread_join(thread_handles[i], &thread_retvals[i]);
}

pthread_mutex_destroy(&MUTEX_LOG);

fclose(fp);

return 0;
}
4 changes: 3 additions & 1 deletion src/log.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ extern "C"
#include "log_conf.h"
#endif

#define LOGC_VERSION "0.1.1"
#define LOGC_VERSION_MAJOR 0U
#define LOGC_VERSION_MINOR 2U
#define LOGC_VERSION_TEST 0U

/// @brief Log event struct
typedef struct
Expand Down

0 comments on commit 82f6063

Please sign in to comment.