Skip to content

Instantly share code, notes, and snippets.

@khanzf
Created August 25, 2017 04:26
Show Gist options
  • Save khanzf/465eec49d5008f460aa0571604267d7b to your computer and use it in GitHub Desktop.
Save khanzf/465eec49d5008f460aa0571604267d7b to your computer and use it in GitHub Desktop.
FreeBSD taskqueue(9) example
SRCS=taskqueue_example.c
KMOD=taskqueue_example
.include <bsd.kmod.mk>
/* This is an example taskqueue(9) on FreeBSD.
* All it does is create a scheduled task and execute it almost immediately.
* I wrote this because I did not understand the taskqueue(9) man page, so I
* read the FreeBSD kernel source.
* My question: https://docs.freebsd.org/cgi/getmsg.cgi?fetch=12990+0+current/freebsd-hackers
* Answer: https://docs.freebsd.org/cgi/getmsg.cgi?fetch=17373+0+current/freebsd-hackers
*/
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h>
#include <sys/errno.h>
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/queue.h>
#include <sys/taskqueue.h>
#include <sys/malloc.h>
void static threadqueue_example_proc(void *, int);
void init_threadqueue_example(void);
struct taskqueue;
struct taskq {
struct taskqueue *tq_queue;
} *tq;
struct controller {
struct task x_task;
} *ctrl;
static void
threadqueue_example_proc(void *arg, int npending) {
char *str = arg;
printf("Got message: %s\n", str);
}
void
init_threadqueue_example()
{
tq = malloc(sizeof(struct taskq), M_TEMP, M_WAITOK);
ctrl = malloc(sizeof(struct controller), M_TEMP, M_WAITOK);
TASK_INIT(&ctrl->x_task, 0, threadqueue_example_proc, "Farhan");
tq->tq_queue = taskqueue_create("farhan", M_NOWAIT | M_ZERO,
taskqueue_thread_enqueue, &tq->tq_queue);
taskqueue_start_threads(&tq->tq_queue, 1, PI_DISK, "%s name", "ABC");
taskqueue_enqueue(tq->tq_queue, &ctrl->x_task);
}
static int
threadqueue_example_loader(struct module *m, int what, void *arg)
{
int err = 0;
switch (what) {
case MOD_LOAD:
init_threadqueue_example();
uprintf("Repeater KLD loaded.\n");
break;
case MOD_UNLOAD:
uprintf("Repeater KLD unloaded.\n");
break;
}
return(err);
}
static moduledata_t threadqueue_example_mod = {
"taskqueue_example",
threadqueue_example_loader,
NULL
};
DECLARE_MODULE(threadqueue_example, threadqueue_example_mod, SI_SUB_KLD, SI_ORDER_ANY);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment