-1

I'm looking for solution how to break infinite loop, when the thread will be finished. code is quite complicated, so i show u only the main part. Look below

 for(;;){     if(stan==false)
              pthread_create(&counter, NULL, count_me, NULL);     
              //to create thread only once in loop

              stan=true;

                  move=getchar();
                  //(...) action.... doesn't matter     
         }

As you see, main are waiting for user move in getchar() func. I want to break this loop, after 10 sec from create a thread.

thread def below

        void *count_me(void *threadid)
        {
           sleep(10);

           pthread_exit(NULL);

         }

thx for your help

  • You can't break an infinite loop. If it's breakable, it's not infinite. Anyway, just use a global variable - `volatile int endLoop = 0;`, and set it to 1 from the other thread. Check it each time in the loop. – sashoalm Feb 05 '15 at 09:59
  • I think you actually want to cancel the `getchar`. If I understood correctly, this approach may help you out: http://stackoverflow.com/questions/11513593/cancelling-getchar – alediaferia Feb 05 '15 at 10:05

2 Answers2

0

A simple way is to add a flag that is set by the thread when it exits, the main thread can then check this flag and call pthread_join and break out of the loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0
 for(;;) 
     {   
          if(breakloop != 0)
          {
          if(stan==false) 
          pthread_create(&counter, NULL, count_me, NULL);     
          //to create thread only once in loop

          stan=true;

              move=getchar();
              //(...) action.... doesn't matter
          }
          else
          { 
              break; 
          } 
     }

This should work. Change the breakloop to 1 or something else when you want to break the loop. In your case, create a timer for example.