--- libaitsched/src/tasks.c 2012/08/08 08:15:24 1.11.2.1 +++ libaitsched/src/tasks.c 2012/08/21 11:07:16 1.12.4.1 @@ -3,7 +3,7 @@ * by Michael Pounov * * $Author: misho $ -* $Id: tasks.c,v 1.11.2.1 2012/08/08 08:15:24 misho Exp $ +* $Id: tasks.c,v 1.12.4.1 2012/08/21 11:07:16 misho Exp $ * ************************************************************************** The ELWIX and AITNET software is distributed under the following @@ -1132,3 +1132,73 @@ schedCallOnce(sched_root_task_t * __restrict root, sch _sched_unuseTask(task); return ret; } + +/* + * schedThread() - Add thread task to scheduler queue + * + * @root = root task + * @func = task execution function + * @arg = 1st func argument + * @detach = Detach thread from scheduler, if !=0 + * @opt_data = Optional data + * @opt_dlen = Optional data length + * return: NULL error or !=NULL new queued task + */ +sched_task_t * +schedThread(sched_root_task_t * __restrict root, sched_task_func_t func, void *arg, int detach, + void *opt_data, size_t opt_dlen) +{ +#ifndef HAVE_LIBPTHREAD + sched_SetErr(ENOTSUP, "Not supported thread tasks"); + return NULL; +#endif + sched_task_t *task; + void *ptr; + pthread_t tid; + pthread_attr_t attr; + + if (!root || !func) + return NULL; + + /* get new task */ + if (!(task = _sched_useTask(root))) + return NULL; + + task->task_func = func; + TASK_TYPE(task) = taskTHREAD; + TASK_ROOT(task) = root; + + TASK_ARG(task) = arg; + + TASK_DATA(task) = opt_data; + TASK_DATLEN(task) = opt_dlen; + + if (root->root_hooks.hook_add.thread) + ptr = root->root_hooks.hook_add.thread(task, NULL); + else + ptr = NULL; + + if (!ptr) { + pthread_mutex_lock(&root->root_mtx[taskTHREAD]); + TAILQ_INSERT_TAIL(&root->root_thread, TASK_ID(task), task_node); + pthread_mutex_unlock(&root->root_mtx[taskTHREAD]); + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, detach ? + PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE); + if (pthread_create(&tid, &attr, + (void *(*)(void*)) task->task_func, task)) { + LOGERR; + pthread_mutex_lock(&root->root_mtx[taskTHREAD]); + TAILQ_REMOVE(&root->root_thread, TASK_ID(task), task_node); + pthread_mutex_unlock(&root->root_mtx[taskTHREAD]); + task = _sched_unuseTask(task); + } else + TASK_VAL(task) = (u_long) tid; + pthread_attr_destroy(&attr); + } else + task = _sched_unuseTask(task); + + return task; +} +