我上一个答案的代码
#define REENTRANT
//The above is neccessary when using threads. This must be defined before any includes are made
//Often times, gcc -DREENTRANT is used instead of this, however, it produces the same effect
#include <pthread.h>
char running=1;
void* timer(void* dump){
unsigned char i=0;
while(running){
for(i=0;i<300 && running;i++){
sleep(1);//so we don't need to wait the 300 seconds when we want to quit
}
if(running)
callback();//note that this is called from a different thread from main()
}
pthread_exit(NULL);
}
int main(){
pthread_t thread;
pthread_create(&thread,NULL,timer,NULL);
//do some stuff
running=0;
pthread_join(thread,NULL);//we told it to stop running, however, we might need to wait literally a second
pthread_exit(NULL);
return 0;
}