Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A pthread_cancel problem

Status
Not open for further replies.

maluk

Programmer
Oct 12, 2002
79
SG
Hello all!

I am experimenting with pthreads. Now I have encountered an unexpected behavior (at least I think it is). The code is show below:

Code:
#include <iostream>
#include <pthread.h>

using namespace std;

void* task(void* arg)
{
        cout << "Starting task" << endl;
        for(int count = 0; count < 1000; ++count)
        {
                cout << "Thread working " << count << endl;
                if((count % 100) == 0)
                {
                        cout << "******* YO *********" << endl;
                        pthread_testcancel();
                        cout << "******* DIGG *********" << endl;
                }
        }
}


int main(int argc, char* argv[])
{
        void* status;
        pthread_t mt;
        pthread_create(&mt, NULL, task, NULL);

        sleep(1000);

        pthread_cancel(mt);
        pthread_join(mt, &status);
        if(status == PTHREAD_CANCELED)
                cout << "Thread cancelled" << endl;

        cout << "Done" << endl;
}

The output of the code above is:

[tt]
...
...
Thread working 699
Thread working 700
******* YO *********
******* DIGG *********
Thread working 701
Thread working 702
...
...
Thread working 799
Thread working 800
******* YO *********
******* DIGG *********
Thread working 801
Thread working 802
...
...
Thread working 997
Thread working 998
Thread working 999
[/tt]

After "Thread working 999", it just hangs there. It's like a deadlock or something. Actually what I was expecting was that the thread will exit when it reached 100 but as you can see, it continued 'till 999.

Can anyone tell me what's wrong?
I am trying this on Ubuntu Dapper Drake with g++ 4.0.3.

Thanks!

Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
It would but I am tryinh to undestand thread cancellation which is why I used pthread_cancel and pthread_testcancel.

Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top