How to Cancel a Thread

S

Steven

Hello

I need some help with canceling a thread.
Here is a simple code that creates and cancels a thread. It does create a
thread BUT it doesnt cancel it, am I doing this wrong?
Thank you!

#include <pthread.h>
#include <stdio.h>
#include<iostream.h>

void* work(void* arg){ while (1); }
int main()
{
int tmp=0;
pthread_t thread;
process=pthread_create(&thread,NULL,work,NULL);
pthread_cancel(thread); // this doesnt work

cin>>tmp>>tmp;
return 0;
}
 
G

Gianni Mariani

Steven said:
Hello

I need some help with canceling a thread.
Here is a simple code that creates and cancels a thread. It does create a
thread BUT it doesnt cancel it, am I doing this wrong?
Thank you!

Very sorry - this is off-topic in c.l.c++ - try comp.unix.programmer ...

readt the faq ...

http://www.parashift.com/c++-faq-lite/

However - just a hint - this idea of asynchronously stopping a thread is
really bad. In a well behaved system, a thread may be "notified" to
stop itself but it is up to the thread to terminate. Your work thread
sits in an infinite loop - you need to teach it to terminate.

Read the man-page on pthread_cancel. The first paragraph on my man page
discusses exactly this thing.
 
A

Alexander Terekhov

Steven said:
Hello

I need some help with canceling a thread.
Here is a simple code that creates and cancels a thread. It does create a
thread BUT it doesnt cancel it, am I doing this wrong?

You're doing it wrong. You need to have either a cancelation point or
async-cancel-safe region in your work() function. Note that there are
two types of cancelation points -- "shall occur" and "may occur". The
entire async-cancel-safe region behaves like "may occur" point (I mean
that thread cancelation "may occur" at any point inside the region if
it isn't disabled). And don't forget to make your thread routine extern
"C"... and to pray that thread cancelation works in a non-braindamaged
way under your C++ implementation (but that's unlikely, unfortunately).
Stay away from async cancel if don't understand async cancel safety.
Add pthread_testcancel() to you loop and it "will work".

regards,
alexander.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,373
Latest member
Desiree036

Latest Threads

Top