How to join threads created dynamically in c/c++ - c++

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.

Related

How do I create multiple C++ threads without blocking the main thread using join()?

I have a simple TCP client/server in C++ and I am currently spawning a thread per connected user to handle messages, however I have run into a few issues and I'm not sure how to solve them as I am unfamiliar with the standard C++ threading.
When a client connects to the server, a thread is created for that client until they are disconnected using something like
clientThread = thread(processMessages);
clientThread.join();
This thread will persist for the lifetime of the client. As I have called join() on this thread, when client 2 connects while client 1 is still connected, it is blocked by the join() call.
Removing this join() call means that when a client disconnects, the thread is destroyed causing a terminate() error due to it being joinable.
How can I make this client thread just process in the background while the main thread can just continue and accept new connections?
Just showing how you can store created thread objects:
std::vector<std::thread> threads;
threads.emplace_back(processMessages);
...
for (auto & t : threads) t.join();
However, as others pointed out in comments, creating a thread for each new connection might not be the best approach.

How to stop and destroy thread from main thread (from which is created)

I need to create, run, stop thread and then again same process (reloading some new data and need to refresh and cannot use C++11 standard). I have created and run thread like from mine main thread
pthread_t p;
pthread_create(&p, NULL, calculation, some_pointer_to_object);
How to stop and destroy this thread from main thread ?
(pthread_exit is from current thread).
You need to use pthread_cancel().
The only clean way to do so is this: Set up a flag in the main thread, start the thread, poll the flag in your new thread and finish fast if it's set. Everything else but letting your new thread close itself down cleanly on request opens a boatload of cans of worms, and that's an understatement.

How to check boost thread is running and Kill it

In my program, it start a boost thread and keep the handler as a member of the main thread.
When user press the cancel button I need to check the started thread still running and if it is running need tho kill that specific thread. here is the pseudo code.
cheating thread
int i =1;
boost::thread m_uploadThread = boost::thread(uploadFileThread,i);
This is the method use to check if thread is still running, but it is not working
boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(2);
if (this->uploadThread.timed_join(timeout)){
//Here it should kill the thread
}
The return value true means the thread is completed before the call times out. And looks like what you want is
if(!this->uploadThread.timed_join(timeout))
For stop your thread you can use:
my_thread.interrupt();
in order this to work you have to set an interruption point at the point you want the thread's function stops when you interrupt.
Note: the interruption by it self don't stop the thread it just set a flag and the when an interruption point is reached the thread is interrupted. If no interruption point is found, the thread don't stop.
You can also handle the interrupted exception boost::thread_interrupted that way you can do things depending on if the thread was interrupted or not.
For instance lets assume the next code is inside a thread function:
try
{
//... some important code here
boost::this_thread.interruption_poit(); // Setting interrutption point.
}
catch(boost::thread_interrupted&)
{
// Now you do what ever you want to do when
// the thread is interrupted.
}

Running a server in a simple pthread

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.

Infinite Loop until application gets signal

I have an application which starts 5 threads.
After starting those threads nothing happens in main().
main(){
`start thread 1..5
}
How do I loop infinitely in main() so my program will run continuously until it gets a signal.
I don't want to use
while(true)
because it will eat CPU cycle. (As I think )
Edit:
I am using gcc 4
Thread Api :pthread
OS : Linux
the simplest would be:
while (true) sleep(1000);
and the best would be to join() all the five threads.
The sigsuspend() function is designed for precisely this purpose - it will suspend the calling thread until it recieves a signal that results in the calling of a signal handler.
To avoid a race condition (where the signal arrives just before your process calls sigsuspend()), you should block the signal, check for it, then pass a mask to sigsuspend() that unblocks it:
/* Block SIGUSR1 */
sigset_t sigusr1set, origset;
sigemptyset(&sigusr1set);
sigaddset(&sigusr1set, SIGUSR1);
sigprocmask(SIG_BLOCK, &sigusr1set, &origset);
/* Set up threads etc here */
/* Unblock SIGUSR1 and wait */
sigdelset(&origset, SIGUSR1);
sigsuspend(&origset);
Join those threads see pthread_join.
You could try the Boost::Synchronization functions, like this:
main(){
`start thread 1..5
wait for signal
exit
}
Windows? Use WaitForMultipleObjects.