线程池


// 定义任务函数,用于模拟需要执行的任务
void *mytask(void *arg)
{
 int n = (int)arg;

 // 输出任务信息和需要花费的时间
 printf("[%u][%s] ==> job will be done in %d sec...\n",
  (unsigned)pthread_self(), __FUNCTION__, n);

 sleep(n); // 模拟任务执行时间

 // 输出任务完成信息
 printf("[%u][%s] ==> job done!\n",
  (unsigned)pthread_self(), __FUNCTION__);

 return NULL;
}

// 定义计时函数,用于每秒打印一个计时秒数
void *count_time(void *arg)
{
 int i = 0;
 while(1)
 {
  sleep(1);
  printf("sec: %d\n", ++i); // 输出计时秒数
 }
}

int main(void)
{
 pthread_t a;
 pthread_create(&a, NULL, count_time, NULL); // 创建打印计时秒数的线程

 // 初始化线程池
 thread_pool *pool = malloc(sizeof(thread_pool));
 init_pool(pool, 2);

 // 添加任务到线程池
 printf("throwing 3 tasks...\n");
 add_task(pool, mytask, (void *)(rand()%10)); // 添加任务到线程池
 add_task(pool, mytask, (void *)(rand()%10)); // 添加任务到线程池
 add_task(pool, mytask, (void *)(rand()%10)); // 添加任务到线程池

 // 检查活动线程数
 printf("current thread number: %d\n", remove_thread(pool, 0)); // 移除空闲线程
 sleep(9);

 // 再次添加任务到线程池
 printf("throwing another 2 tasks...\n");
 add_task(pool, mytask, (void *)(rand()%10)); // 添加任务到线程池
 add_task(pool, mytask, (void *)(rand()%10)); // 添加任务到线程池

 // 添加线程到线程池
 add_thread(pool, 2); // 增加线程数

 sleep(5);

 // 从线程池移除线程
 printf("remove 3 threads from the pool, current thread number: %d\n", remove_thread(pool, 3)); // 从线程池移除线程

 // 销毁线程池
 destroy_pool(pool); // 销毁线程池
 return 0;
}
posted @ 2024-06-10 23:13  头像被封了  阅读(5)  评论(0编辑  收藏  举报