免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2088 | 回复: 3
打印 上一主题 下一主题

[C] 我的C语言新手-通用线程池 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-12-10 21:35 |只看该作者 |倒序浏览
最近写的线程池公用开发库,带一个简单的测试代码,使用了队列进行线程分批。可以同时创建多个线程池。欢迎大家指点批正。

直接运行 make ,然后执行生成的 pools 测试程序。

下面是核心部分代码:

int pool_dispatch(pool* pl, void(*cb)(void*), void* arg)
{
    pool_thread* thread;
    pool_queue_item* item;

    pthread_mutex_lock(&(pl->mutex));
    if(0 == pl->idle_total)
    {
        pthread_mutex_unlock(&(pl->mutex));
        return 2;
    }

    /* get from queue of idle threads */
    pl->idle_total--;
    item = pool_queue_get(pl->idle_threads);
    if(NULL != item)
    {
        thread = (pool_thread*)item->data;
        thread->cb = cb;
        thread->arg = arg;
        pthread_cond_signal(&(thread->cond));
    }
    pthread_mutex_unlock(&(pl->mutex));

    return 0;
}

void* pool_warpper(void* arg)
{
    pool_thread* thread = (pool_thread*)arg;
    pool* pl = (pool*)thread->parent;

    for(; 0 == pl->stop;)
    {
        pthread_mutex_lock(&(thread->mutex));
        pthread_cond_wait(&(thread->cond), &(thread->mutex));

        if((0 == pl->stop) && (NULL != thread->cb))
        {
            thread->cb(thread->arg);
        }

        pthread_mutex_unlock(&(thread->mutex));

        /* put into queue of idle thread */
        pthread_mutex_lock(&(pl->mutex));
        pool_queue_put(pl->idle_threads, &(thread->queue));
        pl->idle_total++;
        pthread_mutex_unlock(&(pl->mutex));
    }

    return NULL;
}

pools.rar

2.31 KB, 下载次数: 126

论坛徽章:
1
2017金鸡报晓
日期:2017-01-10 15:19:56
2 [报告]
发表于 2007-12-11 10:19 |只看该作者
pl->idle_total--;
    item = pool_queue_get(pl->idle_threads);
    if(NULL != item)
    {
        thread = (pool_thread*)item->data;
        thread->cb = cb;
        thread->arg = arg;
        pthread_cond_signal(&(thread->cond));
    }

pl->idle_total--;放到if语句里面会不会好一点

论坛徽章:
0
3 [报告]
发表于 2007-12-11 15:07 |只看该作者
对,多谢提醒。

论坛徽章:
0
4 [报告]
发表于 2007-12-11 18:49 |只看该作者
原帖由 lowellzhong 于 2007-12-10 21:35 发表
最近写的线程池公用开发库,带一个简单的测试代码,使用了队列进行线程分批。可以同时创建多个线程池。欢迎大家指点批正。

直接运行 make ,然后执行生成的 pools 测试程序。

下面是核心部分代码:

in ...



看了一下代码,释放线程池的时候,没有妥善地处理,有可能会导致非法内存访问。
可以对照一下这个实现 threadpool
  1. void destroy_threadpool(threadpool destroyme)
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP