2-2 linear optimization technique pool

Line application Origin of pool

  To meet multiple clients can simultaneously landing requirements, the server must implement concurrent work . When the server main process keeps waiting for client connection, each connection on a client needs a separate process or thread processing client tasks . However, considering the multiple processes of system resource consumption , there is a single thread repeatedly create and destroy such action excessive scheduling overhead , so the use of Linear pool.

  Linear pool is a multithreaded concurrent processing form, it is a good bunch of threads have been created. Given a new task -> Remove idle thread processing tasks  -> task processing is completed into the thread pool to wait. Avoid a lot of repetition to create a thread dealing with short-term task, the cost of destruction, very suited for continuous produce a large number of concurrent tasks.


  Wire line pool implementation process principles:

1 ) Initial setting task queue (list) as a buffer mechanism, and initializes create n threads , locking to take a task queue task runs (multithreading mutex) .

2 ) In the processing task process , when the job queue is empty, all threads are blocked (blocking the IO ) is idle ( the wait ) state;

3 ) When the task queue to join a new task queue lock , and then use the condition variable wake-up ( Work ) in the blocking of a thread to perform the task ;

4 ) implementation of the latter again return to the thread pool becomes idle ( the wait ) state, sequentially or wait for the next task.

  Finally, to complete all tasks will thread pool threads in the unity destroyed .


  Framework of the accession process:

the main main function:
 // 1. Initialize thread pool 
    pool_init ( . 5 );
 //    wait for connecting 
    the while ( . 1 ) 
    { 
        new_fd = Accept (sockfd, ( struct the sockaddr *) (& client_addr), & sin_size);       
         // 2. performed process, the task to process the thread pool 
        pool_add_task (process, new_fd); 
    } 

void pool_init (int max_thread_num) 
{ 
the pool -> ThreadID = (pthread_t *) the malloc (* max_thread_num the sizeof (pthread_t)); // the application stack space 
    for ( = I 0 ; I <max_thread_num; I ++) //3
    {  
        pthread_create (&(pool->threadid[i]), NULL, thread_routine, NULL); //创建线程  保存线程id
    } 
}

int pool_add_task (void *(*process) (int arg), int arg) 
{
/*构造一个新任务 初始化*/ 
    Cthread_task *task = (Cthread_task *) malloc (sizeof (Cthread_task)); 
    task->process = process; 
    task->arg = arg; 
    task->next = NULL;
    pthread_mutex_lock (&(pool->queue_lock)); 
~~~~~~
    pthread_mutex_unlock (&(pool->queue_lock)); 
    a pthread_cond_signal (& (pool-> queue_ready)); // wake-up thread 
    return  0 ; 
} 

void * Process (int Arg) // read operator, reads the corresponding command response

Guess you like

Origin www.cnblogs.com/hjh-666/p/11234413.html