multithreading - Concurrent TCP server in C that adjust its size. -
my aim create server connected many clients (but rather limited number). clients running on mobile phones in lan. there can 2 mobile phones, can 10 mobile phones. wouldn't limit max number of phones ahead.
i think tcp communication phone rather longer (not simple request/response rather longer dialog between both). thread pool seems better suited many connection, rather short request/response.
i think best using simple pthreads. possibly create 1 pthread per 1 connection mobile phone.
but here may doubts there can appear many such connections , number of pthreads large. think limiting number of connections example 10 @ same time , in order next mobile phone able connect such server there connected phone must disconnect.
i have done this:
int cs_fd; printf("waiting new connections on main thread...\n"); while(1) { cs_fd = accept_new_connection(ps_fd); if(cs_fd == failure) { fprintf(stderr, "accept_new_connection: failed!\n"); return failure; } else if(cs_fd == continue) { continue; } // handle new connection on concurrent thread connection_thread(cs_fd, conn_handler); }
but doesn't limit number of threads , connection. how can such thing?
- limit number of child threads max_num_of_threads.
- accept() new connection if limit not exceeded.
- if num of child thread equal max_num_of_threads wait accepting new connection until else disconnects.
- if disconnects can accept new connection.
- client should info cannot connect because there many connections (connected devices) , must wait.
i think this:
int cs_fd; pthread_t conn_threads[max_num_of_threads]; printf("waiting new connections on main thread...\n"); while(1) { for(int i=0; i<max_num_of_threads; i++) { cs_fd = accept_new_connection(ps_fd); // check cs_fd correct conn_threads[i] = connection_thread(cs_fd, conn_handler); } // here problem waits until child threads finish // not 1 resume accepting new connections for(int i=0; i<max_num_of_threads; i++) { pthread_join(&conn_threads[i], null); } }
now think whether usage of waiting/signaling couldn't help. maybe usage of pthread_cond_wait() when there max limit reached , pthread_cond_signal() when child thread exiting.
in case of client know why cannot connect maybe should make separate thread separate udp server request/response exchange of server status codes.
is there reason want spawn threads each connection? why not have list of connections, use 'select()' see who's sending info, , deal info. if dealing info takes while, can hand off threads (if free).
that's kind of pushing problem further processing, possible if keep pushing , pushing down need it, may not need threads @ all.
Comments
Post a Comment