开发项目中函数指针的应用

现在有很多个任务(函数),我们需要将多个任务(函数)添加到任务链表中,任务用函数指针表示即可,在这里,需要说明的是,处理多任务时需要考虑到多任务资源的处理,用的是互斥锁来解决。
首先我们定义一些变量:

struct Work
{
  void (*function)(int); //任务函数
  int argv;  
  Work* next;
};

struct Pool
{
  int number;
  int quit;
  Work* head;  //任务头指针
  pthread_t* pth;   //线程标识符
  pthread_mutex_t mutex;  //互斥锁
  pthread_cond_t cond;
};

任务添加到链表中,用的是单链表头插法实现的。

int add_function(void(*fun)(int),int fd)
{
    if(pool == NULL)
        perror("pool初始化失败");
    if(pool->head != NULL)
       perror("head 指向空失败");
       
    Work* cur=new Work;
    assert(cur != NULL);
    //任务函数添加
    cur->function=fun;
    cur->argv=fd;
    cur->next=nullptr;

   pthread_mutex_lock(&pool->mutex);
   //头插
   cur->next=pool->head;
   pool->head=cur;
   pthread_mutex_unlock(&pool->mutex);
   pthread_cond_signal(&pool->cond); 
   return 0;  
}

猜你喜欢

转载自blog.csdn.net/qq_40008325/article/details/88908440