#include "thread.h" static thread_attr_t thdAttrs[THREAD_ID_MAX]={ //name fn arg stacksize prio {"ws", NULL, NULL, 2*KB, 1}, {"web", NULL, NULL, 4*KB, 1}, {"snmp", NULL, NULL, 2*KB, 1}, {"power", NULL, NULL, 2*KB, 1}, {"polling", NULL, NULL, 2*KB, 1}, {"mqtt", NULL, NULL, 2*KB, 1}, {"mail", NULL, NULL, 2*KB, 1}, {"ui", NULL, NULL, 2*KB, 1}, }; static thread_handle_t thdHandles[THREAD_ID_MAX]={0}; int thread_start(int id, thread_fn fn, void *arg) { if(id<0 || id>=THREAD_ID_MAX || !fn) { return -1; } thread_attr_t *attr=&thdAttrs[id]; attr->fn = fn; attr->arg = arg; return thread_startEx(id, attr->name, attr->fn, attr->arg, attr->stksz, attr->prio); } int thread_start2(int id) { if(id<0 || id>=THREAD_ID_MAX) { return -1; } thread_attr_t *attr=&thdAttrs[id]; if(!attr->fn) { return -1; } return thread_startEx(id, attr->name, attr->fn, attr->arg, attr->stksz, attr->prio); } int thread_restart(int id) { if(id<0 || id>=THREAD_ID_MAX) { return -1; } thread_attr_t *attr=&thdAttrs[id]; if(!attr->fn) { return -1; } thread_stop(id); return thread_startEx(id, attr->name, attr->fn, attr->arg, attr->stksz, attr->prio); } int thread_startEx(int id, const char *name, thread_fn fn, void *arg, int stksz, int prio) { int r; pthread_attr_t attr; thread_handle_t *h=NULL; if(id<0 || id>=THREAD_ID_MAX || !fn) { return -1; } h = &thdHandles[id]; if(h->running) { return -1; } h->name = name; h->arg = arg; h->quit = 0; r = pthread_attr_init(&attr); if(r) { printf("____ thread %d attr init failed\n", id); return -1; } #if 1 r = pthread_attr_setstacksize(&attr, stksz); if(r) { printf("____ thread %d attr setstacksize %d failed\n", id, stksz); } #endif r = pthread_create(&h->tid, &attr, fn, h); if(r==0) { h->running = 1; #if 0 r = pthread_setschedprio(h->tid, prio); if(r) { printf("____ set thread prio %d failed\n", prio); } #endif } pthread_attr_destroy(&attr); return r; } int thread_stop(int id) { if(id<0 || id>=THREAD_ID_MAX) { return -1; } thread_handle_t *h=&thdHandles[id]; h->quit = 1; //pthread_detach(); pthread_join(h->tid, NULL); h->tid = 0; h->running = 0; h->arg = NULL; h->fn = NULL; return 0; } int thread_stop_all(void) { int i; for(i=0; i=THREAD_ID_MAX) { return 0; } thread_handle_t *h=&thdHandles[id]; return h->running; } int thread_start_simp(thread_fn fn, void *arg, int stksz) { int r; pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, stksz); r = pthread_create(&tid, &attr, fn, arg); pthread_attr_destroy(&attr); return r; } int thread_print_stacksize(void) { int r; size_t size; pthread_attr_t attr; r = pthread_attr_init(&attr); if(r) { printf("___ print stacksize, attr init failed\n"); return -1; } r = pthread_attr_getstacksize(&attr, &size); if(r) { printf("___ print stacksize, attr init failed\n"); } else { printf("_____ stacksize: %dMB\n", size/(1024*1024)); } pthread_attr_destroy(&attr); return r; }