How can I exit or stop a thread immediately?
How can I make it stop immediately when the user enters an answer? I want it to reset for every question.
Here's my code where threading is involved
int q1() {
int timer_start;
char ans[] = "lol";
char user_ans[50];
timer_start = pthread_create( &xtimer,NULL,(void*)timer_func,(void*)NULL);
printf("What is the capital city of Peru?\n");
while(limit){
scanf("%s",user_ans);
if(limit)
{
if(!strcmp(user_ans, ans))
{
// printf("YAY!\n");
score++;
// q2();
}
else
{
game_over();
}
}
}
}
Based on your code I can give a simple answer:
In this case do not use threads at all.
You do not need them. Store the start time, let the user answer, check the time again after user gives an answer.
To answer your question:
You should use a mutex-protected or volatile variable to asynchronously communicate between threads. Set that variable from one thread and check it in another. Then reset its value and repeat. A simple snippet:
Using
pthread_cancel()
is an option, but I would not suggest doing it. You will have to check the threads state after this call returns, sincepthread_cancel()
does not wait for the actual thread stop. And, which to me is even more important, I consider using it ugly.@Naruil's suggestion to call pthread_cancel() is pretty much the best solution i found, but it won't work if you didn't do the following things.
According to the man-page of pthread_cancel the pthread_cancelibility depend on two thing
thread_cancel_state is PTHREAD_CANCEL_ENABLE by default, so our main concern is about the thread_cancel_type, it's default value is type PTHREAD_CANCEL_DEFFERED but we need PTHREAD_CANCEL_ASYNCHRONOUS to set on that thread, which we wan't to cancel.
Following an example given::
run it using gcc filename.c -lpthread and output the following:: count -- 0 count -- 1 count -- 2 count -- 3 count -- 4
note that the done is never printed because the thread was canceled when the i became 5 & the running thread was canceled. Special thanks @Naruil for the "pthread_cancel" suggestion.
You can simply call
pthread_cancel
on that thread to exit it. And you can send SIGSTOP/SIGCONT signal viapthread_kill
to stop/restart it.But if all you want is a timer, why must you thread?
Using methods to stop a thread is a brute way. You should rather politely ask the thread to stop by signalling. Thereby the thread will have an option to tidy after itself e.g. if it has allocated memory, which it will not have any opportunity to do if the thread is cancelled.
The method is relatively simple and comprises no OS signalling:
define a thread state variable or structure outside the thread. Point to it at the pthread_create and dereference the state variable in the thread.
It is even possible to communicate with the thread using a structure provided that it is simple 'atomic' variables or a simple handshake mechanism is established. Otherwise it may be necessary to use mutex. Use pthread_join to wait for threads to terminate.