linux - Design of multi-threaded server in c -


when trying implement simple echo server concurrent support on linux.

following approaches used:

  • use pthread functions create pool of thread, , maintained in linked list. it's created on process start, , destroy on process termination.
  • main thread accept request, , use posix message queue store accepted socket file descriptor.
  • threads in pool loop read message queue, , handle request gets, when there no request, block.

the program seems working now.

the questions are:

  • is suitable use message queue in middle, efficient enough?
  • what general approach accomplish thread tool needs handle concurrent request multiple clients?
  • if it's not proper make threads in pool loop & block retrieve msg message queue, how deliver requests threads?

this seems unneccesarily complicated me. usual approach multithreaded server is:

  • create listen-socket in thread process
  • accept client-connections in thread
  • for each accepted client connection, create new threads, receives corresponding file descriptor , work
  • the worker thread closes client connection, when handled

i not see benefit in prepopulating thread-pool here.

if want threadpool:

i use linked list accepted connections , pthread_mutex synchronize access it:

  • the listener-process enqueues client fds @ tail of list.
  • the clients dequeue @ head.

if queue empty, thread can wait on variable (pthread_cond_wait) , notified listener process (pthread_cond_signal) when connections available.

another alternative

depending on complexity of handling requests, might option make server single-threaded, i.e. handle connections in 1 thread. eliminates context-switches altogether , can performant.

one drawback is, 1 cpu-core used. improve that, hybrid-model can used:

  • create 1 worker-thread per core.
  • each thread handles simultaneously n connections.

you have implement mechanisms distribute work amongst workers.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -