半同步/半反應堆模型(使用線程池)的TCP伺服器例子,反應堆tcp

來源:互聯網
上載者:User

半同步/半反應堆模型(使用線程池)的TCP伺服器例子,反應堆tcp

在半同步/半非同步模式中“同步”和“非同步”與I/O模型中同步、非同步概念不同:I/O模型中,同步和非同步區分的是核心嚮應用程式通知的是何種I/O事件(是就緒事件還是完成事件),以及該由誰來完成I/O讀寫(是應用程式還是核心)。在併發模式中,“同步”指的是程式完全按照代碼序列的順序執行;“非同步”指的是程式的執行需要由系統事件來驅動(常見的系統事件包括中斷、訊號)。

非同步線程的執行的執行效率高,即時性強,但是編寫以非同步方式執行的程式相對複雜,難以調試和擴充,而且不適合大量的並發。而同步線程雖然效率相對較低,但是邏輯簡單。對於伺服器這種既要求較好的即時性,又要求能同時處理多個客戶請求的應用程式,可以同時使用同步線程和非同步線程實現。非同步線程監聽客戶請求,將其封裝成請求對象插入請求隊列中。請求隊列通知某個在同步模式下的背景工作執行緒來讀取並處理該對象。最簡單的選背景工作執行緒的是Round Robin演算法,也可以使用條件變數或訊號量。
是半同步/半非同步變形:“半同步/半反應堆模型”:

所示模型缺點:(1)主線程和背景工作執行緒共用請求隊列。主線程新增工作和背景工作執行緒從隊列取任務都要對請求隊列加鎖,消耗CPU時間。(2)每個背景工作執行緒在同一時間僅處理一個客戶請求。如果客戶資料多,而背景工作執行緒少,則請求隊列中任務堆積,客戶響應會越來越慢。可以通過增加背景工作執行緒來解決。是相對高效的半同步半非同步模式:

  該模式的主線程只管理監聽socket,串連socket由背景工作執行緒來管理。當有新的串連到來時,主線程就接受並將新返回的串連socket派發給某個背景工作執行緒,此後該新socket上的任何I/O操作都由被選中的線程來處理,直到客戶關閉串連。的每個線程都維護自己的事件迴圈,它們各自獨立監聽不同事件。因此每個線程都是非同步模式。
  
   下面代碼所示的伺服器程式使用主線程來監聽通訊端並接收資料,將接收的資料存放在一個隊列中(通過擷取互斥鎖來在隊列中存放元素),在隊列中存入資料後發送訊號到條件變數訊號,然後釋放互斥鎖,以允許線程池中某個線程為這個客戶服務。線程池裡的背景工作執行緒通過試圖擷取互斥鎖,擷取隊列元素並對其進行處理(這裡僅僅在控制台顯示資料)。

//http_parse.cpp#include "http_parse.h"//錯誤處理函數void err_exit(const char *info) {    perror(info);    exit(-1);}//設定描述符為非阻塞模式int setnonblocking(int fd) {    int old_option = fcntl( fd, F_GETFL );    int new_option = old_option | O_NONBLOCK;    fcntl( fd, F_SETFL, new_option );    return old_option;}//向epoll中添加要監聽的描述符void addfd(int epollfd, int fd) {    epoll_event event;    event.data.fd = fd;    event.events = EPOLLIN | EPOLLET;    epoll_ctl( epollfd, EPOLL_CTL_ADD, fd, &event );    setnonblocking( fd );}//任務隊列,主線程收到的資料隊列,等待線程池線程處理queue<char *> taskqueue; //用於為任務隊列加鎖的互斥鎖和通知的條件訊號量pthread_mutex_t clifd_mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t clifd_cond = PTHREAD_COND_INITIALIZER;vector<pthread_t> thread_pool(3); //線程池int main(int argc, char **argv) {    struct sockaddr_in servaddr;    memset(&servaddr, 0, sizeof(servaddr));    servaddr.sin_family = AF_INET;    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);    servaddr.sin_port = htons(9877);    int listenfd = socket(AF_INET, SOCK_STREAM, 0);    if (-1 == listenfd)        err_exit("socket error");    int opt = 1;    if (-1 == setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))        err_exit("setsockopt error");    if (-1 == bind(listenfd, (const struct sockaddr *)&servaddr,        sizeof(servaddr)))        err_exit("bind error");    if (-1 == setnonblocking(listenfd))        err_exit("make_socket_non_blocking error");    if (-1 == listen(listenfd, 1000))        err_exit("listen error");    struct epoll_event event, events[MAX_EVENTS];    int epollfd = epoll_create(5);    if (-1 == epollfd)        err_exit("epoll_create error");    event.data.fd = listenfd;    event.events = EPOLLIN;    if (-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &event))        err_exit("epoll_ctl error");    //建立線程池    int i;    for (i = 0; i < 3; ++i)        thread_make(i);    for ( ; ; ) {        int i;        int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);        for (i = 0; i < nfds; ++i) {            if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) ||                !(events[i].events & EPOLLIN)) {                    fprintf(stderr, "epoll error\n");                    continue;            }            else if (listenfd == events[i].data.fd) {                for ( ; ; ) {                    struct sockaddr cliaddr;                    socklen_t clilen = sizeof(cliaddr);                    int connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen);                    if (-1 == connfd) {                        if ((errno == EAGAIN) || (errno == EWOULDBLOCK))                            break;                        else                            err_exit("accept error");                    }                    if (-1 == setnonblocking(connfd))                        err_exit("setnonblocking connfd error");                    event.data.fd = connfd;                    event.events = EPOLLIN | EPOLLET; //邊緣觸發、讀事件                    if (-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &event))                        err_exit("epoll_ctl add connfd error");                }                continue;            }            else if(events[i].events & EPOLLIN ) {                int done = 0;                int nread = 0;                char buf[65535];                int count;                while((count = read(events[i].data.fd, buf + nread, sizeof(buf))) > 0) {                    nread += count;                }                if (count == -1 && errno != EAGAIN) {                    done = 1;                    err_exit("read error");                }                else if (0 == count)                    done = 1;                buf[nread] = '\0';#ifdef DEBUG                write(STDOUT_FILENO, buf, nread);                write(STDOUT_FILENO, "\n", 1);                printf("nread: %d\n", nread);                write(STDOUT_FILENO, "\n\n", 2);#endif                pthread_mutex_lock(&clifd_mutex);                if (strlen(buf) > 4)                    taskqueue.push(buf);                //taskqueue.push(string(buf));                pthread_cond_signal(&clifd_cond);                pthread_mutex_unlock(&clifd_mutex);                if (done) {#ifdef DEBUG                    printf("close: %d\n", events[i].data.fd);#endif                    epoll_ctl(epollfd, EPOLL_CTL_DEL, events[i].data.fd, 0);                }            }            else {}        }    }    close(listenfd);    return 0;}//線程建立函數void thread_make(int i) {    void *thread_worker(void *);    pthread_create(&thread_pool[i], NULL, &thread_worker, (void*)i);    return;}//回呼函數,供線程建立函數調用void *thread_worker(void *arg) {#ifdef DEBUG    printf("thread %d starting\n", (int)arg);#endif    for ( ; ; ) {        pthread_mutex_lock(&clifd_mutex);        //如果任務隊列為空白則等待隊列資料到來        while (0 == taskqueue.size())            pthread_cond_wait(&clifd_cond, &clifd_mutex);#ifdef DEBUG        printf("\ndd %s\n\n", taskqueue.front());#endif        //將隊列首元素出隊        taskqueue.pop();        pthread_mutex_unlock(&clifd_mutex);    }}
//http_parse.h#ifndef HTTP_PARSE_H#define HTTP_PARSE_H#include <queue>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <assert.h>#include <stdio.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <fcntl.h>#include <stdlib.h>#include <sys/epoll.h>#include <signal.h>#include <sys/wait.h>#include <sys/mman.h>#include <sys/stat.h>#include <fcntl.h>#include <string>#include <pthread.h>#define MAXNCLI 100#define MAX_EVENTS 1024#define SERV_PORT 9877using namespace std;void thread_make(int i);int iput, iget;int setnonblocking(int fd);void addfd(int epollfd, int fd);void err_exit(const char *info);#endif

  測試伺服器的用戶端是文章《unix網路編程》(15)poll函數以及使用poll的客戶服務器程式中的用戶端。
  是服務端測試:

著作權聲明:本文為博主原創文章,from http://blog.csdn.net/u013074465。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.