I'm trying to make my small multi client server run in a pthread so that the clients may receive and send data to the database.
At the moment I can telnet to the server, send a message to the server and it will be echoed back. I'd like to take the clients input and "use" it and send an answer to him.
The only way I can accomplish that is if I put the server in a thread I assume.
So I created a simple thread and called the server function from it but the server wont start for some reason. What am I doing wrong?
void *startServer(void *)
{
cout << "Starting server\n";
Server();
}
int main()
{
pthread_t t;
pthread_create(&t, NULL, &startServer, NULL);
cout << "Hello";
return 0;
}
The only thing that shows after I run it is
Hello
You aren't waiting for the thread, the main thread exits before the server thread can do anything, you need to do a pthread_join in the main thread, say, for example, after printing hello.
pthread_join(t, NULL);
C++ immediately exits the process at the end of main, regardless of any other threads that are executing. As opposed to e.g. Java, which waits for all non-daemon threads to finish, IIRC.
If you want to wait till other threads are finished, you need to use pthread_join.
Related
I want to write a simple C++ chat server. Simplifying:
void clientThread(int sock){
// receives data on socket and sends to all other client's
//sockets which are held in a vector, when received data<0 thread is
// finished and client is removed from a vector
}
Main loop:
vector<thread> th;
while(1){
memset(&rcvAddr,0,sizeof(sockaddr_in));
sock=accept(connectSocket,NULL,(socklen_t*)&addrLength);
cout << "client connected from: " << inet_ntoa(rcvAddr.sin_addr)<< endl;
if(sock<0)
continue;
mtx.lock();
clientDescriptors.push_back(sock);
mtx.unlock();
th.pushback(thread(&server::clientThread,this,sock));
}
And I have a problem with the last line. This vector constantly grows, do you know any proper way to manage this? How to spawn these threads? Are there any implemented data structures, or something like this, to manage threads? I read about thread Pool, but I think this does not solve this problem.
One (proper) design may be :
A thread Pool which manages a connections queue
A listening thread which accepting Sockets repeatedly
a Psuedo code may be :
main:
launch thread pool
launch the listening thread
block until server is not neaded
listening thread routine:
while true
accept a client socket
build a task out of the client socket
push the task into the connection queue
the task is the actual function/function object/object which does something meaningfull with the socket, like reading it's content, write result to client, close the socket.
It is going to keep growing, because this is what you do - you create a thread for every connection. Occasionally threads exit, but you never get to removing elements from this vector, since you are not joining threads.
Best thing to do would be to join all joinable threads from the vector automatically, but to my ongoing dismay posix completely lacks this feature - you can only join one thread at a time. Posix arrogantly states that If you believe you need this functionality, you probably need to rethink your application design. - which I do not agree with. On any rate, one thing you can do is to use thread pools - they are going to help you.
Say that I have two threads, the main thread and a thread that is dedicated to continuously listening on a standard TCP socket. Now, say that at some point I want to shutdown everything. From the main thread, I would like to close the connection the listening thread is working on, then join the thread and end the program.
However, this is tricky, since I don't know how to make the listening thread return from the call to read. That call won't return unless something actually is received, and in principle I could be waiting for a long long time until the other endpoint decides to send me something.
When I was working with UDP sockets, I used to work around this problem by sending a packet on that port from my loopback interface, therefore triggering a return from recvfrom. However, this is terribly inelegant and it cannot be done on a TCP socket.
I know that another workaround could be to set a timeout with setsockopt: in this way I am guaranteed that the call will eventually return, but this is inelegant as well, and also quite inefficient since I could be waiting for several seconds before being able to join the thread.
So I was wondering if there is some way to trigger an EAGAIN on a socket read call, not unlike the one I would get on a timeout, so that on my main thread I could just call some force_returnon my socket descriptor and the call to read on the other thread would return?
I usually solve this problem by creating a pipe() and using select() in the reading thread. The reading thread must select on both the TCP socket and one end of the pipe. Whenever you want to shut down the reader, set a flag and write some data to the other end of the pipe.
Setup:
#include <unistd.h>
int signalPipe[2];
...
pipe(signalPipe);
Reader:
while(running)
{
FD_ZERO(&fds);
FD_SET(tcpSocket, &fds);
FD_SET(signalPipe[0], &fds);
select(max(tcpSocket, signalPipe[0]) + 1, &fds, NULL, NULL, NULL);
...
}
Other thread:
// We want to stop now.
running = false;
write(signalPipe[1], "foo", 3);
I have a windows service where I am receiving http requests and launching a process for it which might run more than an hour . I need to get notified in main service when a process ends .And when service is ended i need to terminate all child processes . I understand that if I do waitforsingleobject it will hang on windows service until the process is completed , and no further http requests will be entertained ? I am doing following for now which works but its not correct approach .
if(CreateProcess( TEXT(EXEPATH),
procArguments,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi )
)
{
processHandles[processCount] = pi.hProcess;
processStreams[processCount] = eventId.c_str();
processCount++;
}
On Service stop I am doing this
for(int index=0;index<10;index++){
g_pAppLog->Log("Stop Process for processStreams[%d] %s\n",index,processStreams[index].c_str());
int terminationResult = TerminateProcess(processHandles[index],1);
}
The functions WaitForSingleObjectEx and WaitForMultipleObjectsEx allow you to specify a timeout, so that the function will not hang forever.
You can thus call the function in a loop, checking if the process has really terminated, or it's just a timeout expiration.
Anyway, you should not WaitFor anything, unless you have nothing better to do.
If you have a web server, you should listen to connection and spawn responding processes.
If you just want to check if a process terminated, you can call GetExitCodeProcess.
So, summing up, you might either:
Run a loop that:
accepts a request;
spawns a process;
checks if any of the previously created process terminated (without blocking);
Make a two-thread application, with one thread accepting requests, and the other one calling WaitForMultipleObjectsEx in a loop, and possibly handling children termination.
In your main service, you should create a thread to do that, so the main thread can still be running.. In this thread, you should use WaitforMultipleObjects to wait for all the child process to end, once a process is ended, the corresponding code will be execute.
Please check the MSDN for details
Do the waiting in a different thread than the one that is processing SCM requests. Use CreateEvent() to create a waitable manual-reset event, then have the waiting thread use WaitForMultipleObjects() to wait on both the event and the child process at the same time. WaitForMultipleObjects() will tell you which one is signaled first. When the service is being stopped, signal the event with SetEvent(). When the child process exits, its handle will be signaled. If the event gets signaled first, the waiting thread can call TerminateProcess() on the child process.
I have written a C/C++ code which implements socket connection and the main thread is in continuous loop listening at its port. When a connection request comes at this port, I have spawned a thread using pthread calls and offloaded the work on this thread. As such i have 'n' threads getting created dynamically for 'n' incoming requests.
The problem is that, if one thread terminates the main thread also terminates.
I have used pthread_join() but It waits for the thread in the argument to finish.In my case, the new threads are not getting spawned once the call to pthread_join() is made.
pthread_t t;
while(1) //server always to be in listen mode
{
client_len=sizeof(client_sockaddr);
client_sockfd=accept(server_sockfd,(struct sockaddr*)&client_sockaddr,&client_len);
pthread_create(&t,NULL,server_thread,(void*)client_sockfd);
(void)pthread_join(t,NULL);
}
If you don't care about the return value from your threads, and you're not interested in when they complete, then you should detach them with pthread_detach or simply create them in a detached state to begin with:
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
while(1) //server always to be in listen mode
{
client_len=sizeof(client_sockaddr);
client_sockfd=accept(server_sockfd,(struct sockaddr*)&client_sockaddr,&client_len);
pthread_t t;
pthread_create(&t,&thread_attr,server_thread,(void*)client_sockfd);
}
pthread_attr_destroy(&thread_attr);
Add printf("check string\n"); after pthread_join in your code. compile and run it now. You might get some idea about your problem.
You will not meet printf function.
Reason for the behavior is pthread_join will wait for first created thread to finish the job.
so unless and until first thread finish the job new thread will not created. So your code will not accept any new client connection.
So don't use pthred_join inside your while(1) then your problem will be solved.
pthread_join is mostly useful when main process want to wait until thread finishes the job.
I have to run a task in background using thread in C++. Actually in code i have to send multiple HTTP request using curl and i don't want to run using Main thread as it will put main thread blocked untill task is completed. Hence I want for each http request is should be something like that :
a) a new thread is created b) send the curl req on this new thread c) once req/response is done, send response/data back to main thread
During this process i want Main thread to be free and run some other its own task. I am new to C++ and threading, please advise how to achieve this.
If you want your main thread to be notified as soon as the worker thread is done then it sounds like you need to have a message processing loop in the main thread.
I'm just thinking this can be implemented the same way as the window procedure in WinAPI. Something along these lines.
cEvent event;
while( true )
{
event = GetNextEvent();
if( event.GetType() == APPQUIT )
{
break;
}
if( event.GetType() == SENDHHPTREQUEST )
{
// Create worker thread etc.
}
else if( event.GetType() == HTTPREQUESTCOMPLETED )
{
// Process HTTP request resuts.
}
...
}
The worker thread needs a way to send events to the main thread. And of course adding, removing events from the message queue must be thread-safe, i.e. protected with mutexes. And I guess all the data required to create a request or to process results of a request needs to be somehow packaged into cEvent.
You need to use a condition variable or auto or manual reset event to notify your main thread. You get your main thread to wait for this condition variable when you've started your secondary thread, and when the secondary thread is done, it signal's the flag which lets the main thread know it's done and can continue doing what it's doing.
if you are using c++11 standard, I had to make a "main thread caller" which takes a lambda of code and schedules it to call on main thread next time the screen updates (which is always on the main thread). Internally it uses a vector of lambdas and drains it every time update is called. If there is no lambdas, update is not scheduled. I use it extensively in my iOS/Droid production code.
you can get it here:
https://github.com/radif/emjCCMainThreadCaller