2

I am using boost and trying to create a basic thread_group that will perform their tasks and exit. Here's what my code looks like:

boost::thread_group threads;
void InputThread()
{
    int counter = 0;

    while(1)
    {
        cout << "iteration #" << ++counter << " Press Enter to stop" << endl;

        try
        {
            boost::this_thread::sleep(boost::posix_time::milliseconds(500));
        }
        catch(boost::thread_interrupted&)
        {
            cout << "Thread is stopped" << endl;
            return;
        }
    }
}

int main()
{
    int iterator;
    char key_pressed;
    boost::thread t[NUM_THREADS];

    for(iterator = 0; iterator < NUM_THREADS; iterator++)
    {
        threads.create_thread(boost::bind(&InputThread)) ;
        cout << "iterator is: " << iterator << endl;

           // Wait for Enter to be pressed      
        cin.get(key_pressed);

        // Ask thread to stop
        t[iterator].interrupt();

    }
    // Join all threads
    threads.join_all();

    return 0;
}

I started with two threads and fall in an infinite loop after both the threads are done with their jobs. Something like below:

iterator is: 0
iteration #1 Press Enter to stop
iteration #2 Press Enter to stop

iterator is: 1
iteration #1 Press Enter to stop
iteration #3 Press Enter to stop
iteration #2 Press Enter to stop

iteration #4 Press Enter to stop
iteration #3 Press Enter to stop
iteration #5 Press Enter to stop
iteration #4 Press Enter to stop
iteration #6 Press Enter to stop
iteration #5 Press Enter to stop
iteration #7 Press Enter to stop
^C

Where am I going wrong?

08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
ND_27
  • 764
  • 3
  • 8
  • 26

1 Answers1

1

There's no relationship drawn between your boost::thread t[] and boost::thread_group threads;.

So t[iterator].interrupt(); has no effect on the threads spawned by threads.create_thread(boost::bind(&InputThread)) ;.

Instead do:

std::vector<boost::thread *> thread_ptrs;
// ...

    thread_ptrs.push_back(threads.create_thread(boost::bind(&InputThread)));

    // ...

    thread_ptrs[iterator].interrupt();

Aside: the name "iterator" is often used for types and makes a poor value to iterate over. Use i or some other idiomatic name for this value.

Brian Cain
  • 14,403
  • 3
  • 50
  • 88
  • Thanks, that solves the issue. I will need better understanding of thread_group though. – ND_27 Sep 26 '13 at 18:33
  • @user2816953 If you're satisfied with the answer, please upvote and/or accept the answer accordingly. – Brian Cain Sep 26 '13 at 22:36
  • I already accepted the answer but still do not have enough reputation to upvote. I just signed up two days back. When I get there, I will return your favor of answering by voting up :) – ND_27 Sep 27 '13 at 17:58