#include "mysignal.h" #include "pthread.h" #include "stdlib.h" #include "lambda.h" #include "sys/time.h" #include "errno.h" #include "stdio.h" #include "string.h" typedef struct { SIG_OBJ; int test_var; }test_sig_obj; typedef struct { SIG_OBJ; int test_var; }test_sig_obj2; // 定义槽函数 slot test_slot(test_sig_obj2* self, int a, int b) { printf("test_slot var=%d\n", self->test_var); self->test_var = a + b; printf("test_slot var=%d\n", self->test_var); } // 定义信号 signal test_signal(test_sig_obj* self, int a, int b); // 以下是自动生成的代码示例 // 把槽函数的参数封装为结构体 typedef struct { slot_list_with_pars slot_; test_sig_obj2* self; int a; int b; }test_signal_args; // 封装函数用来调用实际的槽函数 static void test_slot_func(void* args) { test_signal_args* a = args; printf("test_slot_func: %d %d\n", a->a, a->b); printf("args_p=%p\n", a); test_slot(a->self, a->a, a->b); } // 信号函数的实现 signal test_signal(test_sig_obj* self, int a, int b) { test_signal_args* pars = NULL; slot_list* slot_p = self->__sig_obj.slot_head; while (slot_p) { pars = calloc(1, sizeof(test_signal_args)); pars->slot_.func = slot_p->func; // 这里self要换成槽的self pars->self = slot_p->slot_obj; pars->a = a; pars->b = b; if (slot_p->thread) { // 异步调用 send_slot_fun(slot_p->thread, (slot_list_with_pars*)pars); } else { // 同步调用 slot_p->func(pars); free(pars); } slot_p = slot_p->next; } } // 定义一个数据结构来保存槽封装函数与槽函数的关系 typedef struct { void (*func)(void*); char *name; } func_name; static const func_name g_func_table[] = { { .func = test_slot_func, .name = "test_slot" } }; void* signal_find_slot_func(const char* name) { for (int i = 0; i < sizeof(g_func_table) / sizeof(func_name); i++) { if (strcmp(name, g_func_table[i].name) == 0) { return g_func_table[i].func; } } return 0; } // 自动生成代码示例结束 static void mdelay(unsigned long mSec){ struct timeval tv; tv.tv_sec=mSec/1000; tv.tv_usec=(mSec%1000)*1000; int err; do{ err=select(0,NULL,NULL,NULL,&tv); }while(err<0 && errno==EINTR); } static test_sig_obj g_sig_obj = { .test_var = 1, }; static test_sig_obj2 g_sig_obj2 = { .test_var = 2, }; int thread_fun(void* t) { mythread_t* th = sigthread_init(); printf("thread_fun start\n"); printf("test_slot_func=%p\n", test_slot_func); connect(&g_sig_obj, test_signal, th, &g_sig_obj2, test_slot); mdelay(1000); emit test_signal(&g_sig_obj, 2, 3); mdelay(1000); return 0; }