Question

I created two threads in my program. I wanted to terminate thread_1 inside thread_2 function and vice versa based on flag. I tried exit() and pthread_exit(Thread_id) but it does not work. I wanted to cancel the thread execution by calling pthread_cancel but the problem is that I cannot pass the thread id before pthread_create. Any suggestions ??

Was it helpful?

Solution

You can see how pthread_cancel works in the manpage.

However, since you mention C++, why not use the language features? Signaling one or many other threads can be done with condition-variables.

See it Live On Coliru

If you don't have C++11, you can use Boost Threads.

#include <thread>
#include <condition_variable>
#include <iostream>

using namespace std;

struct workers
{
    mutex mx;
    condition_variable cv;
    bool canceled;

    workers() : canceled(false) {}

    void thread1()
    {
        cout << __PRETTY_FUNCTION__ << " start\n";
        this_thread::sleep_for(chrono::seconds(2));

        {
            unique_lock<mutex> lk(mx);
            cout << __PRETTY_FUNCTION__ << " signaling cancel\n";
            canceled = true;
            cv.notify_all();
        }

        this_thread::sleep_for(chrono::seconds(2));
        cout << __PRETTY_FUNCTION__ << " done\n";
    }

    void thread2()
    {
        cout << __PRETTY_FUNCTION__ << " start\n";

        for(;;)
        {
            // do some work
            unique_lock<mutex> lk(mx);
            if (cv.wait_for(lk, chrono::milliseconds(10), [this] { return canceled; }))
                break;
        }

        cout << __PRETTY_FUNCTION__ << " done\n";
    }
};

int main()
{
    workers demo;
    std::thread t1(&workers::thread1, ref(demo));
    std::thread t2(&workers::thread2, ref(demo));

    t1.join();
    t2.join();
}

Output:

void workers::thread1() start
void workers::thread2() start
void workers::thread1() signaling cancel
void workers::thread2() done
void workers::thread1() done

Update The C++03 version with boost is Live On Coliru now too. I've added timestamps for fun:

thread1:21 2014-Mar-26 00:01:40.074269 start
thread2:37 2014-Mar-26 00:01:40.074275 start
thread1:26 2014-Mar-26 00:01:42.074873 signaling cancel
thread2:47 2014-Mar-26 00:01:42.074991 done
thread1:32 2014-Mar-26 00:01:44.075062 done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top