mardi 4 juin 2019

Multi threaded C++ server

Currently, i am trying to explore more about libevent server library "https://github.com/libevent/libevent" came across this github project "https://github.com/frknyldz" i ran this project with main as

main.cpp
#include <winsock2.h>
#include <windows.h>
#include<stdio.h>
#include <csignal>
#include <condition_variable>
#include "HttpServer.h"



#pragma comment(lib,"WS2_32")

std::mutex m;
std::condition_variable cv;

void signalHandler(int signum) 
{
    std::cout << "Sighandler" << std::endl;
    std::cout << "Signal (" << signum << ") received.\n";
    cv.notify_all();


}

void onHello(CHttpRequest *req, void *arg) 
{
    char *data = "<html><body><center><h1>Hello World </h1></center></body></html>";
    req->AddBufferOut(data, strlen(data));
    req->SendReply(HTTP_OK);
}

int main(int argc, char** argv)
{
    WORD wVersionRequested;
    WSADATA wsaData;

    wVersionRequested = MAKEWORD(2, 2);
    WSAStartup(wVersionRequested, &wsaData);

    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);
    CHttpServer server("127.0.0.1", 5555, 5); //Create five threads
    server.SetCallback("/hello", onHello, NULL);
    server.Start();
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk);
    return 0;
}

So here 5 threads get created in this by passing in "CHttpServer server("127.0.0.1", 5555, 5);" i added Sleep in void CHttpRequest::AddBufferOut(const char* data, size_t len) of 5 second as shown below

evbuffer_add(evhttp_request_get_output_buffer(this->req), data, len);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));

Now this is how my Console looks like

Console pic

First five requests run parallel but after that all request gets assigned to same thread. this case occurs when sleep is more than 1 seconds not when it is less one second. Any help would be appreciated. I am using windows 7 VS 2015. I am passing 10 requests using JMeter. You can share your experience with similar bug even if it was encountered in different Programs and measures you had taken.

Thanking in advance

Aucun commentaire:

Enregistrer un commentaire