Moduo: A C++ non-blocking network library for multi-threaded server in Linux.
C++ 11 features
a. functional, bind
in C++11, function declartion can be:
|
|
std::bind() is used to assign existed variables to func parameters during compile-time, and unassigned parameters stand as placeholders, which then replace by real parameters during running-time, and return a new func. bind() can be used to bind static func, global func, class member func.
|
|
threadA.wait(condition_variable);
while(;;)
{
threadB.do();
}
threadB.notify();
threadA.do();
|
|
a simple thread / thread pool lib
take a look at: thread-pool
basically, a task queue to store all todo tasks; a thread pool, to store the worker threads, each of which takes one task from the task queue continuously till the queue empty.
racing condition happens when two threads try to take the same task simultaneously, so mutex. and all operators requrieing thread-safe should use mutex, e.g. enqueue/dequeue task
then callback functors, how each worker thread deal with the task at hand? to design function template with variadic arguments.
a simple Tcp network lib
take a look at: simpleNetwork
in server: socket() -> bind() -> listen() -> accept() –> send()/write()
in client: socket() -> connect() -> recv()/send()
a basic idea is that each connection, the server will create a new thread to handle it. But it consume server quickly.
I/O nonblocking/event-driven & multiplex
|
|
the basic idea of multplex(Linux APIs: poll(), epoll()) is to use one single thread to listen many connections/socket/fd, once any socket is ready for I/O, the thread will execute the write/read callback.
epoll() on success, return the number of revents or 0; on error return -1
|
|