Exit two-threaded program with user input?

Hello,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// clang++ -g -std=c++11 main.cpp -pthread
#include <iostream>
#include <thread>
#include <unistd.h>

void thread1(void)
{
   while(1)
   {
      int i = 88 * 2;
      ::usleep(100000);
   }
   return;
}

void thread3(void)
{
      char ch = 0;
      while(1)
      {
            std::cin >> ch;
            if (ch == 'q') break;
      }
      return;
}

int main()
{
      std::thread th1(thread1);
      std::thread th3(thread3);
      th1.detach();
      th3.join();
      std::cout << "All done\n";
      return 0;
}


Thread1 does some background work, and thread2 is waiting for the user's input.

If I join thread1 then the app can never exit. If I neither join nor detach thread1 then I get "terminate called without an active exception Aborted" which is not a good thing to have.

If I do detach on thread1 does thread1 ever terminate?
If not, how to terminate it?
Also, how do I check if it's terminated or not? -- I realize this is platform specific, I am on Linux.

Thank you.
Last edited on
> If I do detach on thread1 does thread1 ever terminate?
> If not, how to terminate it?

As a general principle, do not terminate threads.

Your background worker thread can periodically check if the program wants to exit.


> how do I check if it's terminated or not? -- I realize this is platform specific

std::thread::native_handle http://en.cppreference.com/w/cpp/thread/thread/native_handle

Or use std::future in conjunction with std::async or std::packaged_task



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <thread>
//#include <unistd.h>
#include <atomic>
#include <future>

std::atomic<bool> quit_now ;

unsigned long long thread1()
{
   unsigned long long i = 0 ;
   while( !quit_now )
   {
      ++i ;
      // ::usleep(100000);
      std::this_thread::sleep_for( std::chrono::microseconds(100) ) ;
   }
   return i ;
}

void thread3()
{
      char ch = 0;
      while(1)
      {
            std::cin >> ch;
            if (ch == 'q') break;
      }
      //return;
}

int main()
{
      std::thread th1(thread1);
      std::thread th3(thread3);
      auto future = std::async( std::launch::async, thread1 ) ;
      std::this_thread::sleep_for( std::chrono::milliseconds(100) ) ;
      
      //th1.detach();
      th3.join();
      
      std::cout << "All done\n";
      quit_now = true ;
      
      th1.join() ; // wait for thread
      std::cout << "loop ran " << future.get() << " times.\n" ; // wait for fututre result
}

http://coliru.stacked-crooked.com/a/85eb2e5177ca465f
-- thank you JLBorges!
Topic archived. No new replies allowed.