How to Use libevent Multithreading

Source: Internet
Author: User

Use C to develop a network on LinuxProgramThe comrades in general are very familiar with the famous libevent. But some new people who are new in this field are confused about this. The original confusion, coupled with the absence of open-source software's "Help Files" style, made these new users very helpless. Fortunately, some enthusiastic friends helped me to save the trouble!

I have been developing a locker server a few days ago. Although the company's existing locker server can work well, It is net and has a poor versatility, when we want to develop a multi-cluster system on Linux, the existing locker Server is a little too tight. Libevent is used during locker server development.

In general, libevent is very useful. One or two functions can solve your complicated network communication work. Of course, this sentence must be used when you are using a single thread. In Linux, process resources are much less lightweight than those in Windows systems, and the cost is not that high, therefore, a lot of software is implemented using the "multi-process" method, such as the well-known Apache. However, in our system, we use the "single-process multi-thread" method, so that we can start multiple processes on a single machine, in order to achieve the "pseudo-distributed" effect to achieve the purpose of testing.

So pay attention to the use of libevent at this time, because it is not thread-safe for event_base. That is to say, multithreading cannot share the same event_base, even the lock operation won't work. At this time, we can only adopt the "single-thread single event_base" policy. My practice is to create a task pool (task object pool). Each task will be executed by a thread. Of course, the thread must also be taken out from the thread pool, during the initialization of the task pool, I initialized the event_base object for each task. In this way, everything is fine.

After paying attention to this area, I began to talk about network communication. When using libevent, the trigger event is when the network connection (or timeout event timeout) is received. Therefore, you need to judge the time source in the event processing function. Second, when libevent receives byte streams for network communication, it uses the buffer in libevnet, therefore, when receiving the event, you must pay attention to accumulating and loop multiple times or register events in event_event. Therefore, in my task, there will be received data. Of course, if your protocol is divided into header and body, usually the header is short, the body is long, and in the client, the header and body are usually sent continuously. In this way, when using libevent, the header and body are received at the same time, so be sure to note that in the function that receives data, you need to distinguish whether the header or body part is received; when the body is very long and exceeds the buffer of libevent, it needs to trigger the receiving function multiple times, in addition to the header and body, you must also note that data must be accumulated when the receiving is incomplete.

When you use libevent and event_set events, you do not need to add event_add multiple times after receiving the data as long as they are not registered using ev_persist. Only when you do not use ev_persist, your event requires multiple event_add events to event_base. Of course, when the event_base function registered with ev_persist is recycled by the task pool, the event_del registration event must be explicitly registered, events that are not registered using ev_persist do not need to be explicitly deleted using event_del.

 Static   Void Read_buffer (Int Client_socket_fd, Short Event_type, Void * Arg ){ If (Null = Arg) {log_error (" File: "_ File __" , Line: % d. Event base Arg is null. ",__ Line __); Return ;} Task_info_t * task_info = (task_info_t *) ARG; If (Event_type = ev_timeout) /* Check whether the event times out. Because I didn't use ev_persist in the event_add event, I need to add an event to the event_base loop when the event times out */ { If (0! = Event_add (& task_info-> on_read, & task_info-> timeout) {log_error (" File: "_ File __" , Line: % d. repeart Add read header event to event_base is error. "); Close (Task_info-> on_read.ev_fd); task_pool_push (task_info );} Return ;} Int Bytes; /* When receiving the header, it may be obtained from the buffer several times. Therefore, a while accumulate */  While (Header = task_info-> read_type) // Recv Header {Bytes = Recv (client_socket_fd, task_info-> header_buffer + task_info-> offset, request_length-task_info-> offset, 0 );If (0> bytes ){ If (Errno = eagain | errno = ewouldblock ){ If (0! = Event_add (& task_info-> on_read, & task_info-> timeout )){ Close (Task_info-> on_read.ev_fd); task_pool_push (task_info); log_error (" File: "_ File __" , Line: % d, "\" Event_add fail. ", _ Line __); Return ;}} Else {Log_error (" File: "_ File __", Line: % d, Recv failed, errno: % d, error info: % s ",__ Line __, errno, strerror (errno )); Close (Task_info-> on_read.ev_fd); task_pool_push (task_info );} Return ;} Else   If (0 = bytes) {log_warning (" File: "_ File __" , Line: % d. Recv buffer form network is error. Disconnection the network. ",__ Line __); Close (Task_info-> on_read.ev_fd); task_pool_push (task_info ); Return ;} If (Request_length> bytes + task_info-> offset) {log_warning (" File: "_ File __" , Line: % d. Recv header is not over. ",__ Line _); task_info-> Offset + = bytes; If (0! = Event_add (& task_info-> on_read, & task_info-> timeout )){ Close (Task_info-> on_read.ev_fd); task_pool_push (task_info); log_error (" File: "_ File __" , Line: % d, "\" Event_add fail. ", _ Line __); Return ;}} Else {Task_info-> read_type = body; deal_request_header (task_info); task_info-> body_buffer = ( Char *) Malloc (Task_info-> request_info.length ); If (Null = task_info-> body_buffer) {log_error (" File: "_ File __" , Line: % d. alloc mem to task_info data is error. ",__ Line __); Close (Client_socket_fd); task_pool_push (task_info ); Return ;} Memset (task_info-> body_buffer, 0, task_info-> request_info.length); task_info-> offset = 0; // Set Recv body buffer offset to 0 Break ;}} /* At this point, it starts to receive the body. Like the header, you must also consider the situation where the body is accumulated multiple times. */  While (Body = task_info-> read_type) {bytes = Recv (client_socket_fd, task_info-> body_buffer + task_info-> offset, task_info-> request_info.length-task_info-> offset, 0 ); If (0> bytes ){ If (Errno = eagain | errno = ewouldblock ){ If (0! = Event_add (& task_info-> on_read, & task_info-> timeout )){ Close (Task_info-> on_read.ev_fd); task_pool_push (task_info); log_error (" File: "_ File __", Line: % d, "\" Event_add fail. ", _ Line __); Return ;}} Else {Log_error (" File: "_ File __" , Line: % d, Recv failed, errno: % d, error info: % s ",__ Line __, errno, strerror (errno )); Close (Task_info-> on_read.ev_fd); task_pool_push (task_info );} Return ;} Else   If (0 = bytes) {log_warning (" File: "_ File __", Line: % d. Recv buffer form network is error. Disconnection the network. ",__ Line __); Close (Task_info-> on_read.ev_fd); task_pool_push (task_info ); Return ;} If (Task_info> request_info.length-task_info-> Offset> bytes) {log_warning (" File: "_ File __" , Line: % d. Recv body is not over. ",__ Line _); task_info-> Offset + = bytes; If (0! = Event_add (& task_info-> on_read, & task_info-> timeout )){ Close (Task_info-> on_read.ev_fd); task_pool_push (task_info); log_error ("File: "_ File __" , Line: % d, "\" Event_add fail. ", _ Line __); Return ;}} Else {Task_info-> read_type = unspecified; Break ;}} Deal_request_body (client_socket_fd, task_info ); Return ;}

 

 Void Deal_working_thread ( Void * Arg) {log_info (" Debug to this. "); Int Client_socket_fd = (Int ) ARG; If (0> client_socket_fd) {log_error (" File: "_ File __" , Line: % d. The ARG means client socket filedesc is less 0! ",__ Line __); Return ;} /* Set the network to non-blocking, which is required by libevent */  If (! Set_nonblocking (client_socket_fd) {log_error (" File: "_ File __" , Line: % d. Set client socket filedesc is error. Error info is % s! ",__ Line __, strerror (errno )); Close (Client_socket_fd );Return ;} Task_info_t * task_info; task_info = task_pool_pop (); /* Register the Event Callback Function for event_base. Note that ev_persist is not used */  Do {Task_info-> read_type = header; event_set (& task_info-> on_read, client_socket_fd, ev_read, read_buffer ,( Void *) Task_info ); If (0! = Event_base_set (task_info-> event_base, & task_info-> on_read) {log_error (" File: "_ File __" , Line: % d. Associate the read header event to event_base is error. ",__ Line _); task_info-> read_type = unspecified; Close (Client_socket_fd); task_pool_push (task_info );Break ;} Event_set (& task_info-> on_write, client_socket_fd, ev_write, response_handle ,( Void *) Task_info ); If (0! = Event_base_set (task_info-> event_base, & task_info-> on_write) {log_error (" File: "_ File __" , Line: % d. Associate the write hander to event_base is error. ",__ Line _); task_info-> read_type = unspecified; Close (Client_socket_fd); task_pool_push (task_info ); Break ;} If (0! = Event_add (& task_info-> on_read, & task_info-> timeout) {log_error ("File: "_ File __" , Line: % d. Add the read header event to event_base is error. ",__ Line _); task_info-> read_type = unspecified; Close (Client_socket_fd); task_pool_push (task_info ); Break ;} Event_base_loop (task_info-> event_base, evloop_nonblock );} While (False ); Return ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.