Exemplo n.º 1
0
int main(int argc, char **argv)
{
    threadpool_t *pool;

    /* 初始化互斥锁 */
    pthread_mutex_init(&lock, NULL);

    /* 断言线程池创建成功 */
    assert((pool = threadpool_create(THREAD, QUEUE, 0)) != NULL);
    fprintf(stderr, "Pool started with %d threads and "
            "queue size of %d\n", THREAD, QUEUE);

    /* 只要任务队列还没满,就一直添加 */
    while(threadpool_add(pool, &dummy_task, NULL, 0) == 0) {
        pthread_mutex_lock(&lock);
        tasks++;
        pthread_mutex_unlock(&lock);
    }

    fprintf(stderr, "Added %d tasks\n", tasks);

    /* 不断检查任务数是否完成一半以上,没有则继续休眠 */
    while((tasks / 2) > done) {
        usleep(10000);
    }
    /* 这时候销毁线程池,0 代表 immediate_shutdown */
    assert(threadpool_destroy(pool, 0) == 0);
    fprintf(stderr, "Did %d tasks\n", done);

    return 0;
}
Exemplo n.º 2
0
int main(int argc, char **argv)
{
    threadpool_t *pool;

    pthread_mutex_init(&lock, NULL);

    pool = threadpool_create(THREAD, QUEUE, 0);
    fprintf(stderr, "Pool started with %d threads and "
            "queue size of %d\n", THREAD, QUEUE);

    while(threadpool_add(pool, &dummy_task, NULL, 0) == 0) {
        pthread_mutex_lock(&lock);
        tasks++;
        pthread_mutex_unlock(&lock);
    }
    fprintf(stderr, "Added %d tasks\n", tasks);

    while(tasks / 2 > done) {
        sleep(1);
    }
    fprintf(stderr, "Did %d tasks before shutdown\n", done);
    threadpool_destroy(pool, 0);
    fprintf(stderr, "Did %d tasks\n", done);

    return 0;
}
Exemplo n.º 3
0
/* \brief Realiza a desalocacao de todos os componentes do servidor
 *
 * \param[out] r_server O servidor
 */
void clean_up_server(server *r_server)
{
  client_node *client;
  file_node *file;
  file_node *next_file;

  unlink(LSOCK_NAME);
  if (r_server->listenfd)
    close(r_server->listenfd);
  if (r_server->l_socket)
    close(r_server->l_socket);
  
  if (r_server->thread_pool.threads)
    threadpool_destroy(&r_server->thread_pool);

  client = r_server->l_clients.head;
  while (client)
    server_client_remove(&client, r_server);

  file = r_server->used_files.head;
  while (file)
  {
    next_file = file->next;
    file_node_pop(file, &r_server->used_files);
    file_node_free(file);
    file = next_file;
  }
}
Exemplo n.º 4
0
threadpool_t*	threadpool_create(int max_thr_num)
{
	int	i = 0;
	pthread_t	td;
	threadpool_t 	*tpool;
	return_null_if_fail(tpool = malloc(sizeof (struct threadpool)));
	tpool->max_thr_num = max_thr_num;
	return_null_if_fail(tpool->thread_id = malloc(max_thr_num*sizeof(pthread_t)));
	return_null_if_fail(tpool->task_queue = malloc(sizeof(struct taskqueue)));
	return_null_if_fail(tpool->task_queue->arg = malloc(max_thr_num*sizeof(void *)));
	return_null_if_fail(tpool->task_queue->task_func = malloc(max_thr_num*sizeof(threadpool_task_func_t)));
	tpool->task_queue->head = tpool->task_queue->tail = 0;
	if (pthread_mutex_init(&tpool->mutex_queue, NULL) != 0)
		return NULL;
	if (pthread_mutex_init(&tpool->mutex_cond, NULL) != 0)
		return NULL;
	if (pthread_cond_init(&tpool->cond, NULL) != 0)
		return NULL;
	while (max_thr_num > 0) {
		if (pthread_create(&td, NULL, threadpool_excute_task, (void *) tpool) == 0) {
			tpool->thread_id[i++] = td;
			--max_thr_num;
			continue;
		}
		threadpool_destroy(tpool);
		tpool = NULL;
		break;
	}
	return tpool;
}
Exemplo n.º 5
0
int main(int argc, char **argv)
{
    threadpool_t *pool;
	int i, k, ret=0;
	void *slave[SLAVE_NUM];
	char *string;

	void *context = zmq_init(1);


    pthread_mutex_init(&lock, NULL);

    pool = threadpool_init(THREAD, QUEUE, 0);
    fprintf(stderr, "Pool started with %d threads and "
            "queue size of %d\n", THREAD, QUEUE);
	if (!pool) {
		return -1;
	}

	for (i = 0; i < 10; i++) {
		/*k = i % 2;
		if (k!=0 && k!=1) {
			ret = -100;
			break;
		}*/
    	ret = threadpool_add(pool, &replay, context, 0);
		if (ret) {
			break;
		}
       	pthread_mutex_lock(&lock);
        tasks++;
        pthread_mutex_unlock(&lock);
	}

    fprintf(stderr, "RET: %d Added %d tasks\n", ret, tasks);

    while(tasks / 2 > done) {
        sleep(1);
    }
    fprintf(stderr, "Did %d tasks before shutdown\n", done);
    fprintf(stderr, "Did %d tasks\n", done);

	slave[0] = zmq_socket (context, ZMQ_REQ);
	zmq_connect (slave[0], "tcp://localhost:5562");
/*
	slave[1] = zmq_socket (context, ZMQ_REQ);
	zmq_connect (slave[1], "tcp://localhost:5563");
*/
	for (i = 0; i < SLAVE_NUM; i++) {
		s_send(slave[i], "END");
		string = s_recv(slave[i]);
		free(string);
		zmq_close(slave[i]);
	}

	zmq_term(context);
    threadpool_destroy(pool, 0);

    return 0;
}
Exemplo n.º 6
0
//*****************************************************************************************
//threadpool_create 函数初始化线程池对象, 成功返回 ThreadPool_ 结构指针, 失败返回 NULL;
//thread_num 为初始化时默认创建的线程数目.
//*****************************************************************************************
ThreadPool* threadpool_create(int thread_num, int max_task_num) {
    ThreadPool *tmp = NULL;
    pthread_t th;
    int i = 0;
 
    if (thread_num > MAX_THREAD_NUM || thread_num < 0)
        return NULL;
    if (thread_num < MIN_THREAD_NUM)
        thread_num = MIN_THREAD_NUM;
    return_null_if_fail(tmp = (ThreadPool *)malloc(sizeof(ThreadPool)));
    tmp->threadnum_ = thread_num;
    tmp->thread_[0] = thread_num;
    tmp->task_queue_ = malloc((max_task_num + 1) * sizeof(void*));
    tmp->curr_task_num = 0;
    tmp->task_fun_ = malloc((max_task_num + 1) * sizeof(void*));
    tmp->start = 0;
    tmp->end = 0;
    tmp->max_task_num = max_task_num;
    if (pthread_mutex_init(&tmp->mutex_, NULL) != 0)
        return NULL;
    if (pthread_cond_init(&tmp->cond_, NULL) != 0)
        return NULL;
    while (thread_num > 0) {
        if (pthread_create(&th, NULL, threadpool_excute_task, (void *) tmp) == 0) {
            tmp->thread_[++i] = th;
            --thread_num;
            continue;
        }
        threadpool_destroy(tmp);
        tmp = NULL;
        break;
    }
    return tmp;
}
Exemplo n.º 7
0
Arquivo: main.c Projeto: pivie/voting
int main(int argc, char **argv)
{
    int i, dup_vote;
    int cores, block_size;
    cores = 16;
    block_size = 1024*1024;
    int *thread;
    file_struct *fs;
    threadpool_t *pool;

    thread = malloc(sizeof(int));

    if(argc<2)
    {
        printf("[usage] vote_counter [-dupvote] [-cores C] [-blocksize B] [filename1] ... [filenameN]\n");
        exit(-1);
    }

    char **file_list = malloc(sizeof(char *) * MAX_FILE_NUM);
    memset(file_list, 0, (sizeof(char*))*MAX_FILE_NUM);

    //analyze input arguments
    if(!(dup_vote = opts(argc, argv, file_list, &cores, &block_size, &thread)))
    {
        exit(-1);
    }
    
    printf("thread number %d\n", *thread);
    //printf("cores %d; block_size %d\n", cores, block_size);
    
    //create pool according to total file size & number
    if((pool = threadpool_create(*thread, cores, 0)) == NULL)
    {
        printf("[error] can not initalize thread\n");
        exit(-1);
    }

    init_mutex();

    dup_vote = dup_vote == 2 ? TRUE : FALSE;

    for (i=0; file_list[i]!=NULL; i++)
    {
        fs = malloc(sizeof(file_struct));
        fs->filename = file_list[i];
        fs->dup_vote = dup_vote;
        fs->block_size = block_size;

        //send read task to thread pool
        threadpool_add(pool, &readfile, fs, 0);

    }

    //wait until all thread finish their job
    threadpool_destroy(pool, 1);

    get_vote_result(3);

    return 0;
}
Exemplo n.º 8
0
int main(int argc, char **argv)
{
    threadpool_t *pool;

    pthread_mutex_init(&lock, NULL);

    assert((pool = threadpool_create(THREAD, QUEUE, 0)) != NULL);
    fprintf(stderr, "Pool started with %d threads and "
            "queue size of %d\n", THREAD, QUEUE);

    while(threadpool_add(pool, &dummy_task, NULL, 0) == 0) {
        /* pthread_mutex_lock(&lock); */
        /* tasks++; */
        /* pthread_mutex_unlock(&lock); */
    }

    /* fprintf(stderr, "Added %d tasks\n", tasks); */

    while((tasks) > done) {
        usleep(10000);
    }
    assert(threadpool_destroy(pool, 0) == 0);
    /* fprintf(stderr, "Did %d tasks\n", done); */

    return 0;
}
Exemplo n.º 9
0
zv_threadpool_t *threadpool_init(int thread_num) {
    if (thread_num <= 0) {
        log_err("the arg of threadpool_init must greater than 0");
        return NULL;
    }

    zv_threadpool_t *pool;
    if ((pool = (zv_threadpool_t *)malloc(sizeof(zv_threadpool_t))) == NULL) {
        goto err;
    }

    pool->thread_count = 0;
    pool->queue_size = 0;
    pool->shutdown = 0;
    pool->started = 0;
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_num);
    /* dummy head */
    pool->head = (zv_task_t *)malloc(sizeof(zv_task_t));
    pool->head->func = NULL;
    pool->head->arg = NULL;
    pool->head->next = NULL;

    if ((pool->threads == NULL) || (pool->head == NULL)) {
        goto err;
    }

    if (pthread_mutex_init(&(pool->lock), NULL) != 0) {
        goto err;
    }

    if (pthread_cond_init(&(pool->cond), NULL) != 0) {
        pthread_mutex_lock(&(pool->lock));
        pthread_mutex_destroy(&(pool->lock));
        goto err;
    }
    
    int i, rc;
    for (i=0; i<thread_num; ++i) {
        if (pthread_create(&(pool->threads[i]), NULL, threadpool_worker, (void *)pool) != 0) {
            threadpool_destroy(pool, 0);
            return NULL;
        }
        log_info("thread: %08x started", pool->threads[i]);

        pool->thread_count++;
        pool->started++;
    }

    return pool;

err:
    if (pool) {
        threadpool_free(pool);
    }

    return NULL;
}
Exemplo n.º 10
0
threadpool_t *threadpool_create(int thread_count, int queue_size, int flags)
{
    threadpool_t *pool;
    int i;

    /* TODO: Check for negative or otherwise very big input parameters */
    printf("in func thread %d\n", thread_count);
    if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL)
    {
	printf("bingo!\n");
        goto err;
    }

    /* Initialize */
    pool->thread_count = 0;
    pool->queue_size = queue_size;
    pool->head = pool->tail = pool->count = 0;
    pool->shutdown = pool->started = 0;

    /* Allocate thread and task queue */
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
    pool->queue = (threadpool_task_t *)malloc
                  (sizeof(threadpool_task_t) * queue_size);

    /* Initialize mutex and conditional variable first */
    if((pthread_mutex_init(&(pool->lock), NULL) != 0) ||
            (pthread_cond_init(&(pool->notify), NULL) != 0) ||
            (pool->threads == NULL) ||
            (pool->queue == NULL))
    {
	printf("bingo!!\n");
        goto err;
    }

    /* Start worker threads */
    for(i = 0; i < thread_count; i++)
    {
        if(pthread_create(&(pool->threads[i]), NULL,
                          threadpool_thread, (void*)pool) != 0)
        {
            threadpool_destroy(pool, 0);
            return NULL;
        }
        pool->thread_count++;
        pool->started++;
    }

    return pool;

err:
    if(pool)
    {
        threadpool_free(pool);
    }
    return NULL;
}
Exemplo n.º 11
0
threadpool_t *threadpool_create(int thread_count, int queue_size, int flags)
{
    if(thread_count <= 0 || thread_count > MAX_THREADS || queue_size <= 0 || queue_size > MAX_QUEUE) {
        return NULL;
    }

    threadpool_t *pool;
    int i;

    /* 申请内存创建内存池对象 */
    if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) {
        goto err;
    }

    /* Initialize */
    pool->thread_count = 0;
    pool->queue_size = queue_size;
    pool->head = pool->tail = pool->count = 0;
    pool->shutdown = pool->started = 0;

    /* Allocate thread and task queue */
    /* 申请线程数组和任务队列所需的内存 */
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
    pool->queue = (threadpool_task_t *)malloc
        (sizeof(threadpool_task_t) * queue_size);

    /* Initialize mutex and conditional variable first */
    /* 初始化互斥锁和条件变量 */
    if((pthread_mutex_init(&(pool->lock), NULL) != 0) ||
       (pthread_cond_init(&(pool->notify), NULL) != 0) ||
       (pool->threads == NULL) ||
       (pool->queue == NULL)) {
        goto err;
    }

    /* Start worker threads */
    /* 创建指定数量的线程开始运行 */
    for(i = 0; i < thread_count; i++) {
        if(pthread_create(&(pool->threads[i]), NULL,
                          threadpool_thread, (void*)pool) != 0) {
            threadpool_destroy(pool, 0);
            return NULL;
        }
        pool->thread_count++;
        pool->started++;
    }

    return pool;

 err:
    if(pool) {
        threadpool_free(pool);
    }
    return NULL;
}
Exemplo n.º 12
0
fv_threadpool_t *threadpool_init(int thread_num)
{
    /* TODO: Check for negative or otherwise very big input parameters */
    if (thread_num <= 0) {
        log_err("the arg of threadpool_init must > 0");
        return NULL;
    }
    /* Initialize */
    fv_threadpool_t *pool;
    if ((pool = (fv_threadpool_t*)malloc(sizeof(fv_threadpool_t))) == NULL) {
        goto err;
    }
    pool->thread_count = 0;
    pool->queue_size = 0;
    pool->shutdown = 0;
    pool->started = 0;
    /* Allocate thread and task queue */
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_num);
    /*此处保留一个空头部,便于插入删除操作*/
    pool->head = (fv_task_t *)malloc(sizeof(fv_task_t));
    pool->head->func = pool->head->arg = pool->head->next = NULL;
    /* Initialize mutex and conditional variable first */
    if (pthread_mutex_init(&(pool->lock), NULL) != 0 ||
            pthread_cond_init(&(pool->cond), NULL) != 0 ||
            pool->threads == NULL ||
            pool->head == NULL)
    {
        goto err;
    }
    /* Start worker threads */
    int i;
    for (i = 0; i < thread_num; ++i)
    {
        if (pthread_create(&(pool->threads[i]), NULL, threadpool_worker, (void *)pool) != 0)
        {
            threadpool_destroy(pool, 0);
            return NULL;
        }
        log_info("thread: %08x started", (unsigned int)pool->threads[i]);
        pool->thread_count++;
        pool->started++;
    }
    return pool;
err:
    if (pool)
    {
        threadpool_free(pool);
    }
    return NULL;
}
int main(void)
{
	threadpool_t pool;
	threadpool_init(&pool,3);
	int i=0;
	for(i=0; i<10; i++)
	{
		int *arg = (int *)malloc(sizeof(int));
		*arg=i;
		threadpool_add_task(&pool,mytask,arg);//往线程池中添加10个任务
	}
	//sleep(10);
	threadpool_destroy(&pool);
	return 0;
}
Exemplo n.º 14
0
int main(void)
{
    struct threadpool *pool = threadpool_init(10, 20);
    threadpool_add_job(pool, work, "1");
    threadpool_add_job(pool, work, "2");
    threadpool_add_job(pool, work, "3");
    threadpool_add_job(pool, work, "4");
    threadpool_add_job(pool, work, "5");
    threadpool_add_job(pool, work, "6");
    threadpool_add_job(pool, work, "7");
    threadpool_add_job(pool, work, "8");
    threadpool_add_job(pool, work, "9");
    threadpool_add_job(pool, work, "10");
    threadpool_add_job(pool, work, "11");
    threadpool_add_job(pool, work, "12");
    threadpool_add_job(pool, work, "13");
    threadpool_add_job(pool, work, "14");
    threadpool_add_job(pool, work, "15");
    threadpool_add_job(pool, work, "16");
    threadpool_add_job(pool, work, "17");
    threadpool_add_job(pool, work, "18");
    threadpool_add_job(pool, work, "19");
    threadpool_add_job(pool, work, "20");
    threadpool_add_job(pool, work, "21");
    threadpool_add_job(pool, work, "22");
    threadpool_add_job(pool, work, "23");
    threadpool_add_job(pool, work, "24");
    threadpool_add_job(pool, work, "25");
    threadpool_add_job(pool, work, "26");
    threadpool_add_job(pool, work, "27");
    threadpool_add_job(pool, work, "28");
    threadpool_add_job(pool, work, "29");
    threadpool_add_job(pool, work, "30");
    threadpool_add_job(pool, work, "31");
    threadpool_add_job(pool, work, "32");
    threadpool_add_job(pool, work, "33");
    threadpool_add_job(pool, work, "34");
    threadpool_add_job(pool, work, "35");
    threadpool_add_job(pool, work, "36");
    threadpool_add_job(pool, work, "37");
    threadpool_add_job(pool, work, "38");
    threadpool_add_job(pool, work, "39");
    threadpool_add_job(pool, work, "40");

    sleep(5);
    threadpool_destroy(pool);
    return 0;
}
Exemplo n.º 15
0
int main() {
    int rc;
    zv_threadpool_t *tp = threadpool_init(THREAD_NUM);
    
    int i;
    for (i=0; i< 100; i++){
        log_info("ready to add num %d", i);
        rc = threadpool_add(tp, sum_n, (void *)i);
        check(rc == 0, "rc == 0");
    }

    if (threadpool_destroy(tp, 1) < 0) {
        log_err("destroy threadpool failed");
    }
    return 0;
}
Exemplo n.º 16
0
Arquivo: test.c Projeto: iguoke/CTP
//gcc -w threadpool.cc -o thread -lpthread
//gcc src.c -std=c99 -o src
//g++ -w -o test test.c  threadpool.c -lpthread
int main()
{
	threadpool_t *thp = threadpool_create(3,100,12);
	printf("pool inited");

	int *num = (int *)malloc(sizeof(int)*20);
	for (int i=0;i<10;i++)
	{
		num[i]=i;
		printf("add task %d\n",i);
		threadpool_add(thp,process,(void*)&num[i]);
	}
	sleep(10);
	threadpool_destroy(thp);
       return 0;
}
Exemplo n.º 17
0
int main(void)
{
    threadpool_t *threadpool = threadpool_init(10);
    int i;
    for(i = 0; i < 1000; i++)
    {
        threadpool_add_work(threadpool, (void *)task1, NULL);
        threadpool_add_work(threadpool, (void *)task2, (void *)i);
    }

    sleep(5);/*so they can handle all of the jobs, or just a bit of them*/
    threadpool_destroy(threadpool);

    //printf("Hello World!\n");
    return 0;
}
Exemplo n.º 18
0
int main( void ) 
{
   threadpool_t pool ; // 定义一个线程池变量
   threadpool_init( &pool, MAX_POOL_SIZE ) ; // 初始化线程池

   // 向线程池中添加 10 个任务,每个任务的处理函数都是 mytask
   for ( int i = 0; i < 10; ++ i ) 
   {
      int* arg = (int*)malloc( sizeof( int ) ) ;
      *arg = i ;
      threadpool_add_task( &pool, mytask, arg ) ;
   }

   threadpool_destroy( &pool ) ; // 销毁线程池
   
   return 0 ;
}
Exemplo n.º 19
0
Arquivo: main.c Projeto: 7ym0n/hack
int main(void)
{
    struct threadpool *pool = threadpool_init(10, 1000);
    int n;
    char s[255];
    //bzero(&s,0x00);
    for(n = 1;n<9;n++){
	//itoa(n,s,4);
	printf("%d",n);
	sprintf(s,"%d",n);
	threadpool_add_job(pool, work, s);
    }

    sleep(5);
    threadpool_destroy(pool);
    return 0;
}
Exemplo n.º 20
0
int main(void)
{
	threadpool_t *thp = threadpool_create(3,100,100);    /*线程池里最小3个线程,最大100个,队列最大值12*/
	printf("pool inited");

	int *num = (int *)malloc(sizeof(int)*20);
    //int num[20];
    int i;
	for (i=0;i<10;i++)
	{
		num[i]=i;
		printf("add task %d\n",i);
		threadpool_add(thp,process,(void*)&num[i]);
	}
	sleep(10);
	threadpool_destroy(thp);
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{

    if ( argc != 3 ) {
        printf("usage: %s numtasks poolsize\n", argv[0]);
        exit(0);
    }

    int NUMTASKS = atoi(argv[1]); //1600 // 16000
    int POOLSIZE = atoi(argv[2]); // 300 //868

    struct timespec tspec;
    long long withpool, nopool, before;
    static long long waittime = 500;

    clock_gettime(CLOCK_REALTIME, &tspec);
    before = timespecToMs(tspec);
    struct threadpool * pool = threadpool_create(POOLSIZE);
    for (int i=0; i < NUMTASKS; ++i) {
        threadpool_enqueue(pool, busywait, &waittime);
    }
    threadpool_destroy(pool);
    clock_gettime(CLOCK_REALTIME, &tspec);
    withpool = timespecToMs(tspec) - before;

    clock_gettime(CLOCK_REALTIME, &tspec);
    before = timespecToMs(tspec);
    pthread_t threads[NUMTASKS];
    for (int i=0; i < NUMTASKS; ++i) {
        pthread_create(&threads[i], NULL, busypthread, &waittime);
    }
    for(int i=0; i < NUMTASKS; ++i) {
        if(pthread_join(threads[i], NULL) != 0) {
            exit(EXIT_FAILURE);
        }
    }
    clock_gettime(CLOCK_REALTIME, &tspec);
    nopool = timespecToMs(tspec) - before;


    printf("Pool runtime: %lld\n",withpool);
    printf("Naked runtime: %lld\n",nopool);

    return 0;
}
Exemplo n.º 22
0
int main()
{
	my_count1 = 0;
	my_count2 = 0;
	pthread_mutex_init(&lock1, NULL);
	pthread_mutex_init(&lock2, NULL);
	threadpool_t *pool = threadpool_create(2);
	
		
	threadpool_add_task(pool, mk_task(f1, NULL));
	threadpool_add_task(pool, mk_task(f2, NULL));
	threadpool_add_task(pool, mk_task(f1, NULL));
	threadpool_destroy(pool, immediate_shutdown);	
	threadpool_add_task(pool, mk_task(f2, NULL));

	pthread_mutex_destroy(&lock1);	
	pthread_mutex_destroy(&lock2);	
	
	printf("my_count1 : %d\n", my_count1);
	printf("my_count2 : %d\n", my_count2);
}
Exemplo n.º 23
0
int main()
{
    fp = fopen("log.txt","w+");

    long long int cost = 0;
    struct timeval tv;
    starttime(&tv);

    thread_pool_t *pool = threadpool_create(2, 4, 10000);
    int i;
    for(i = 0; i < 1000; i++)
    {
        dispatch(pool, test_fun, (void *)i);
    }
    //sleep(5);
    dispatch(pool, test_fun, (void *)i, EMG_PRI);
    threadpool_destroy(pool, 1);

    cost = stoptime(tv);
    printf("%lld\n", cost/1000);

    return 0;
}
Exemplo n.º 24
0
int main(int argc, char *argv[]) {
    long i = 10000;
    threadpool_t *pool = threadpool_create(10, 100, 0);
    assert(pool);
    while (i > 0) {
        if (i % 3 == 0) {
            assert(threadpool_add_task(pool, task3, 
                (void*)(long)(pool->threads_num), 1000) == 0);
        } else if (i % 3 == 1) {
            assert(threadpool_add_task(pool, task2, 
                (void*)(long)(pool->threads_num), 500) == 0);
        } else {
            assert(threadpool_add_task(pool, task1, 
                (void*)(long)(pool->threads_num), 0) == 0);
        }
        i--;
    }

    while (threadpool_task_over(pool, 1, 3) != 0) {};
    threadpool_exit(pool);
    assert(threadpool_destroy(pool, 1, 3) == 0);
    exit(0);
}
Exemplo n.º 25
0
static void run(ctx_t *ctx, int nthreads, int nreqs) {
  if (ctx->pool) {
    /* start using the curl easy handle pool */
    if (!rcvr_pool_open(ctx->pool)) DIE("pool open failed");
  }

  threadpool_t *pool = threadpool_create(nthreads, nreqs, 0);

  for (int i = 0; i < nreqs; i++) {
    if (threadpool_add(pool, &do_request, ctx, 0) < 0)
      DIE("thread pool failed");
  }

  while (ctx->nreq < nreqs) usleep(10);

  threadpool_destroy(pool, 0);

  if (ctx->pool) {
    /* close the pool after use */
    if (!rcvr_pool_close(ctx->pool)) DIE("pool close failed");
  }

  fprintf(stderr, "\n");
}
Exemplo n.º 26
0
bool threadpool_create(struct threadpool * pool, const uint32_t size)
{
    bool ret = false;
    uint32_t i = 0;
    struct threadpool_thread *thread = NULL;

    if (UTILDEBUG_VERIFY((pool != NULL) && (pool->priv == NULL) && (size > 0)))
    {
        pool->priv = UTILMEM_CALLOC(struct threadpool_priv,
                                    sizeof(struct threadpool_priv),
                                    1);

        if (pool->priv == NULL)
        {
            logger_printf(LOGGER_LEVEL_ERROR,
                          "%s: failed to allocate private memory (%d)\n",
                          __FUNCTION__,
                          errno);
        }
        else if (!vector_create(&pool->priv->threads,
                                size,
                                sizeof(struct threadpool_thread)))
        {
            threadpool_destroy(pool);
        }
        else if (!vector_create(&pool->priv->tasks,
                                0,
                                sizeof(struct threadpool_task)))
        {
            threadpool_destroy(pool);
        }
        else if (!cvobj_create(&pool->priv->cv_task))
        {
            threadpool_destroy(pool);
        }
        else if (!cvobj_create(&pool->priv->cv_wait))
        {
            threadpool_destroy(pool);
        }
        else if (!mutexobj_create(&pool->priv->mtx))
        {
            threadpool_destroy(pool);
        }
        else
        {
            for (i = 0; i < vector_getsize(&pool->priv->threads); i++)
            {
                thread = vector_getval(&pool->priv->threads, i);
                memset(thread, 0, sizeof(*thread));

                if (!threadobj_create(&thread->handle))
                {
                    logger_printf(LOGGER_LEVEL_ERROR,
                                  "%s: failed to create thread #%u\n",
                                  __FUNCTION__,
                                  i);
                }
                else if (!threadobj_init(&thread->handle,
                                         threadpool_taskthread,
                                         pool))
                {
                    logger_printf(LOGGER_LEVEL_ERROR,
                                  "%s: failed to initialize thread #%u\n",
                                  __FUNCTION__,
                                  i);
                }
            }

            if (i != vector_getsize(&pool->priv->threads))
            {
                logger_printf(LOGGER_LEVEL_ERROR,
                              "%s: failed to create thread pool\n",
                              __FUNCTION__);
                threadpool_destroy(pool);
            }
            else
            {
                pool->priv->shutdown = true;
                ret = true;
            }
        }
    }
Exemplo n.º 27
0
int main(int argc, char **argv)
{
	struct sigaction sa;
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = 0;
	if(sigaction(SIGPIPE, &sa, NULL)) {
		LOG_ERR("SIGPIPE ERR");
		return 0;
	}

	int listenfd;
	listenfd = open_listenfd(8888);

	make_socket_non_blocking(listenfd);

	int epfd = tiny_epoll_create(0);
	struct epoll_event event;
	event.data.fd = listenfd;
	event.events = EPOLLIN | EPOLLET;
	tiny_epoll_add(epfd, listenfd, &event);

	tiny_threadpool_t *tp = threadpool_init(2);

	while(1) {
		int n = tiny_epoll_wait(epfd, events, MAXEVENTS, -1);
		int i = 0;
		for(;i < n;++i){
			if (listenfd == events[i].data.fd) {
				while(1) {
					struct sockaddr_in clientaddr;
					socklen_t inlen = sizeof(clientaddr);

					int infd = accept(listenfd, (struct sockaddr*)&clientaddr,&inlen);
					if (infd == -1) {
						if((errno == EAGAIN) || (errno == EWOULDBLOCK))
							break;
						else{
							LOG_ERR("accept err");
							break;
						}
					}
					LOG_INFO("new client fd : %d",infd);

					make_socket_non_blocking(infd);

					event.data.fd = infd;
					event.events = EPOLLIN | EPOLLET;
					tiny_epoll_add(epfd, infd, &event);
				}
			}
			else {
				if((events[i].events & EPOLLERR)
						|| (events[i].events & EPOLLHUP)
						|| !(events[i].events & EPOLLIN)) {
					LOG_ERR("epoll error fd : %d",events[i].data.fd);
					close(events[i].data.fd);
					continue;
				}

				LOG_INFO("new task from fd : %d", events[i].data.fd);
				threadpool_add(tp,accept_request,&(events[i].data.fd));
			}
		}
	}
	LOG_INFO("begin destroy");
	if(threadpool_destroy(tp,1) < 0)
		LOG_ERR("idestroy err");

	return 0;

}
Exemplo n.º 28
0
ThreadPool<T>::~ThreadPool()
{	
	if(m_threadpoolIsClosed == false)
		threadpool_destroy();
}
Exemplo n.º 29
0
int main(int argc, char ** argv)
{
	int listen_fd, epfd;
	int epoll_events_count;
	struct epoll_event ev, events[EPOLL_EVENTS_MAX];
	struct sockaddr_in clientaddr;
	socklen_t addrlen;
	int i, serv_port;
	SAK_threadpool_t * tp_handler = NULL;

#if DEBUG
	clock_t tstart;
#endif

	if(argc != 2)
	{
		perror("usage: ./lotus <port>");
		exit(-1);
	}

	serv_port = atoi(argv[1]);
	
	bzero(&clientaddr, sizeof(clientaddr));
	addrlen = sizeof(struct sockaddr_in);

	/*********************** thread pool ***************************/
	tp_handler = threadpool_create(THREADPOOL_THREADS);
	assert(tp_handler != NULL);
	printf("thread pool is created\n");

	/************************** socket *****************************/
	/* make server socket */
	ERR2(listen_fd, make_server_socket(serv_port));
	printf("web server socket is made\n");

	/**************************** epoll ****************************/
	/* create epoll */
	ERR2(epfd, epoll_create(EPOLL_SIZE));
	ev.data.fd = listen_fd;
	ev.events = EPOLLIN|EPOLLET;

	ERR(set_nonblock(listen_fd));
	
	/* add listen_fd to epoll */
	ERR(epoll_ctl(epfd, EPOLL_CTL_ADD, listen_fd, &ev));
	printf("epoll module is created\n");

	
	/* ignore pipe broken signal */	
	signal(SIGPIPE, SIG_IGN);

	/************************* main ********************************/
	for(;;)
	{
		/* wait for changes of fd set */
		ERR2(epoll_events_count, epoll_wait(epfd, events, EPOLL_EVENTS_MAX, EPOLL_TIMEOUT));

#if DEBUG
		tstart = clock();
#endif
		for(i = 0; i < epoll_events_count; i++)
		{

#if DEBUG
			printf("events[%d].data.fd == %d\n", i, events[i].data.fd);
#endif
			if((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN)))
			{
				fprintf(stderr, "ERROR: epoll error\n");
				close(events[i].data.fd);
				continue;
			}
			else if(events[i].data.fd == listen_fd)
			{
#if DEBUG
				printf("Is listen_fd = %d\n", listen_fd);
#endif
				/* a new connection is coming, we accept it 
				   and add the new connection fd to epoll set  */
				while(1)
				{
					int connect_fd;
					char clientaddr_buff[20] = {0};
					connect_fd = accept(listen_fd, (struct sockaddr *)&clientaddr, &addrlen);

					if(connect_fd == -1)
					{
						if((errno == EAGAIN) || (errno == EWOULDBLOCK))
						{
							/* We have process all incoming connection */
							break;
						}
						else
						{
							perror("accept");
							break;
						}
					}
					inet_ntop(AF_INET, &clientaddr.sin_addr, clientaddr_buff, sizeof(clientaddr_buff)), 
					printf("Client [%s : %d] is connected\n", clientaddr_buff, ntohs(clientaddr.sin_port));

					ERR(set_nonblock(connect_fd));
					ev.data.fd = connect_fd;

#if DEBUG
					printf("Get and put connect_fd = %d into epoll\n", connect_fd);
#endif
					ev.events = EPOLLIN|EPOLLET;
					ERR(epoll_ctl(epfd, EPOLL_CTL_ADD, connect_fd, &ev));
				}
				continue;
			}
			else
			{
				/* Can read */

				/************************************************/
				/*  Put the task into thread pool's work queue  */             
				/************************************************/
#if DEBUG
				printf("Is connect_fd = %d\n", events[i].data.fd);
#endif
				threadpool_put(tp_handler, process_request, (void *)events[i].data.fd);
				request_count ++;
				printf("Has handle %d requests\n", request_count);
				//ERR(epoll_ctl(epfd, EPOLL_CTL_DEL, ev.data.fd, &ev));
			}

		}
#if DEBUG
		printf("Statistics: %d events handled at %2.f seconds(s)\n", epoll_events_count, (double)(clock() - tstart)/CLOCKS_PER_SEC);
#endif
	}
	
	close(listen_fd);
	close(epfd);
	threadpool_destroy(tp_handler);
	return 0;
}
Exemplo n.º 30
0
void global_destroy() {
    fclose(log_fp);
    threadpool_destroy(thp, threadpool_specific_way);
    dlclose(handle);
}