Threads exiting prematurely - c++

I have the following piece of code, meant to create two threads and execute them indefinitely. But when run, it exits after some iterations.
#include <iostream>
#include "error.h"
#include <cstdlib>
#include <pthread.h>
#include <string>
#include <time.h>
#include <sys/wait.h>
using namespace std;
#define NUM_THREADS 2
#define TIME_OUT 3
void *GoBackN(void* arg) {
while(true) cout<<"Thread executing"<<endl;
}
int main()
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL);
pthread_create((&t[1]),NULL,&GoBackN,NULL);
wait(NULL);
return 0;
}
Output -
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Process returned 0;
I'm compiling on g++, and running a linux machine.

You have three threads and you allow the main thread to exit.
#include <iostream>
#include "error.h"
#include <cstdlib>
#include <pthread.h>
#include <string>
#include <time.h>
#include <sys/wait.h>
using namespace std;
#define NUM_THREADS 2
#define TIME_OUT 3
void* GoBackN(void* arg) {
while(true) cout<<"Thread executing"<<endl;
}
int main() // main thread starts here
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL); // second thread starts here
pthread_create((&t[1]),NULL,&GoBackN,NULL); // third thread starts here
wait(NULL); // doesn't wait for very long (zero time)
// ...
// main thread keeps running here...
// ...
return 0; // whoops main thread ends closing program
}
You could put an infinite loop (or an infinite wait) in the main thread to stop it exiting the program.
int main()
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL);
pthread_create((&t[1]),NULL,&GoBackN,NULL);
wait(NULL); // doesn't wait for very long (zero time)
// ...
// loop in the main thread too
while(true) cout<<"Main thread executing"<<endl;
// ...
return 0; // now we don't get here
}
Or more typically join the threads waiting for them to exit:
int main() // main thread starts here
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL); // second thread starts here
pthread_create((&t[1]),NULL,&GoBackN,NULL); // third thread starts here
wait(NULL); // doesn't wait for very long (zero time)
// ...
// join threads here
pthread_join(t[0], nullptr);
pthread_join(t[1], nullptr);
// ...
return 0; // we get here when other threads end
}
Now the main thread is suspended and does not consume any CPU time while the other threads are running.
If you are using a modern compiler with C++11 support you can use the Standard Library threads something like this:
#include <thread>
#include <chrono>
#include <vector>
#include <sstream>
#include <iostream>
const int number_of_threads = 5;
// nasty little MACRO to provide synchronized output (crude but works)
#define SYNC_OUT(m) do{std::ostringstream o; o << m << '\n'; std::cout << o.str();}while(0)
void GoBackN(int id) {
while(true)
{
SYNC_OUT("Thread: " << id << " executing");
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
int main() // main thread starts here
{
std::vector<std::thread> threads;
for(int i = 0; i < number_of_threads; ++i)
threads.emplace_back(GoBackN, i); // start new thread
// ...
// join threads here
for(auto&& thread: threads)
thread.join();
}

I'd recommend using <thread> or <future>s std::async. After you create threads, you should either .join() them later or .detach() them, whereas .join() halts the main programs execution and .detach() does not.
#include <thread>
#include <iostream>
void foo()
{
std::cout << "print from thread" << std::endl;
}
int main()
{
std::cout << "before the thread starts" << std::endl;
std::thread t(foo);
t.join();
std::cout << "after thread finishes" << std::endl;
}
For more information you really should check out this for example.

Related

Linux c++: Will blocked threads prevent app process terminating after returning from main function?

This problem is duplicate, but I am still confused about how os will resolve child threads after returning from main function.
Most pepole said that os will invoke exit_group() or exit() to terminate all child threads.
However, I found blocked threads will prevent process terminating.Reading up the documention of linux man page, I didn't find the special works for blocked threads.
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
using namespace std;
mutex m;
condition_variable cv;
int main() {
auto t = thread([]() {
unique_lock<mutex> lock(m);
cv.wait(lock);
});
t.detach();
sleep(1);
cout << "hello" << endl;
return 0;
}
Running above code will print "hello" and then always stuck in blocking.
If simulate the behaviors os to do, directly invoke _exit(2) (be equivalent to exit_group()) in main function, process will terminate normally.
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
using namespace std;
mutex m;
condition_variable cv;
int main() {
auto t = thread([]() {
unique_lock<mutex> lock(m);
cv.wait(lock);
});
t.detach();
sleep(1);
cout << "hello" << endl;
exit(0);
return 0;
}
If use exit() instead of _exit(2), process will be stuck after printing "hello".
So what exactly did os do after returning for main funcion? Will blocked threads prevent process terminating?
The following code will work normally.
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
using namespace std;
mutex m;
condition_variable cv;
int main() {
auto t = thread([]() {
unique_lock<mutex> lock(m);
cv.wait(lock);
});
t.detach();
auto t2 = thread([](){
unique_lock<mutex> lock(m);
cv.wait_for(lock,chrono::seconds(2));
cv.notify_all();
});
t2.detach();
sleep(1);
cout << "hello" << endl;
return 0;
}

C++ killing child thread stops execution of the main thread

I am completely confused with timers and how threads (pthread) work in C++
Timers arent timers but clocks and you cant (I at least cant) kill a thread without killing main thread.
What I need - a bit of code which executes once in 24hrs on a separate thread.
However if the app needs to stop it - I cant do anything but send SIGKILL to it (because join will wait till midnight). Once I kill that thread the app (main thread) seems to kill itself also.
I am open to suggestions.
On condition - I cannot use std::threads and I dont want to wake this thread more than once a day
But easiest for me would be to kill a child thread without stopping execution of the main thread (why this is the case anyway??)
Here is the sample:
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <thread>
#include <pthread.h>
#include <signal.h>
using namespace std;
void* Logger(void* arg) {
int* thread_state = (int*)arg;
cout << "Logger started" << endl;
sleep(24 * 60 * 60);
cout << "Logger thread exiting" << endl;
pthread_exit(0);
}
int main()
{
int thread_state = 0;
pthread_t logger_t;
int rc = pthread_create(&logger_t, NULL, Logger, (void*)&thread_state);
sleep(2);
//thread_state = 1;
pthread_kill(logger_t, SIGKILL);
cout << "i wuz here" << endl;
return 0;
}
output:
Logger started
Killed
I dont know how I missed it but if I call pthread_cancel instead of pthread_kill it works just fine.

Call a function after x seconds while keep running rest of the program in C++

I have a program in which I want to call a function after x seconds or minutes while keep running rest of the program.
You should run new thread:
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
// The function we want to execute on the new thread.
void task(int sleep)
{
std::this_thread::sleep_for (std::chrono::seconds(sleep));
cout << "print after " << sleep << " seconds" << endl;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task, 5);
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}

How I can keep alive the process while one of its threads is killed using pthread in C++?

I have write a program with 3 threads using pthread in c++, and I want to keep alive the process while the thread 1 is killed. here is my program:
#include <unistd.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int a = 0;
void *func (void *arg)
{
int c = a++;
cout << "start thread " << c << endl;
if (c == 1) //I wrote this to thread1 crashes and be killed.
{
int d = 0;
d = 10 / d;
}
cout << "end thread " << c << endl;
}
int main ()
{
pthread_t tid1, tid2, tid3;
pthread_create (&tid1, 0, func, 0);
sleep (1);
pthread_create (&tid2, 0, func, 0);
sleep (1);
pthread_create (&tid3, 0, func, 0);
sleep (10);
return 0;
}
when I run it with "g++ a.cpp -lpthread", the output is like this:
start thread 0
end thread 0
start thread 1
Floating point exception (core dumped)
that means when thread1 is killed, whole the process will be killed. Is there any way to keep alive the process while one of its threads is killed? I need that because I want to use other threads of the process, however anyone of the threads be killed.
note that I don't want to use exception handling to avoid killing the thread.
I solved my problem by ignoring the FPE signal. Here is my new program:
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <signal.h>
using namespace std;
int a = 0;
void sig_func(int sig)
{
//some code we want execute when signal recieves, or nothing.
}
void *func (void *arg)
{
int c = a++;
cout << "start thread " << c << endl;
if (c == 1)
{
int d = 0;
d = 10 / d;
}
cout << "end thread " << c << endl;
}
int main ()
{
pthread_t tid1, tid2, tid3;
signal(SIGFPE,sig_func);
pthread_create (&tid1, 0, func, 0);
sleep (1);
pthread_create (&tid2, 0, func, 0);
sleep (1);
pthread_create (&tid3, 0, func, 0);
sleep (10);
return 0;
}
and its output is like this:
start thread 0
end thread 0
start thread 1
start thread 2
end thread 2
that means when thread1 is killed, whole the process won't be killed and next threads could run their functions.
You may want to use synchronization mechanisms such as semaphores (using sem_wait(), sem_post()) which is shared among multiple threads to induce delay.
Alternate way is to use while(1) and sleep() inside func(), but consumes CPU cycles when awake.

How does thread::detach() work in C++11?

I wrote the following code and am unable to understand why doesn't it prints out all the no's(i.e. 0 to -99) in threadFunc() as it does with main() thread.
#include<iostream>
#include<thread>
#include<string>
#include<mutex>
#include<chrono>
using namespace std;
mutex mu;
void threadFunc(){
for(int i=0;i>-100;i--){
std::this_thread::sleep_for(std::chrono::milliseconds(30)); /*delay for 30ms*/
mu.lock();
cout<<"Thread: "<<i<<endl;
mu.unlock();
}
}
main(){
thread t1(threadFunc);
for(int i=0;i<100;i++){
mu.lock();
cout<<"Main: "<<i<<endl;
mu.unlock();
}
cout<<"End of Main"<<endl;
t1.detach();
}
The output of the program is:
Main: 0
Main: 1
.
.
.
Main: 99
End of Main.
Thread: -1
Process terminates when main() exits, and all threads are killed. You observe this behavior in your program.
Detach basically says that from now on, you can't join this thread. But if you can't join it, you can't make your main() to wait until it completes (unless you use other synchronization primitives) - and thus it is happily exiting.
This is why I strongly discourage everybody from using detached threads, they are very hard to do properly.
The detach function prevents an exception from being thrown when the thread object goes out of scope. Usually, you would want to call join but if you don't want to block the execution you need to call detach. However, you probably need to use another synchronization mechanism to make sure everything is fine if the thread is still running when main is ready to exit. See the following contrived example.
Example Code
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
std::mutex mu;
std::condition_variable cv;
bool finished = false;
void threadFunc()
{
for (int i = 0; i < 5; ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::unique_lock<std::mutex> lock(mu);
std:: cout << "Thread: " << (0 - i) << "\n";
}
std::unique_lock<std::mutex> lock(mu);
finished = true;
cv.notify_one();
}
int main()
{
{
std::thread t1(threadFunc);
t1.detach(); // Call `detach` to prevent blocking this thread
} // Need to call `join` or `detach` before `thread` goes out of scope
for (int i = 0; i < 5; ++i)
{
std::unique_lock<std::mutex> lock(mu);
std::cout << "Main: " << i << "\n";
}
std::cout << "End of Main\n";
std::unique_lock<std::mutex> lock(mu);
cv.wait(lock, [&finished]() { return finished; });
return 0;
}
Example Output
Main: 0
Main: 1
Main: 2
Main: 3
Main: 4
End of Main
Thread: 0
Thread: -1
Thread: -2
Thread: -3
Thread: -4
Live Example
Again, the above is a contrived example and in your case you could more easily use join instead of detach before allowing main to return.