0

I have to extend the execution of current thread for more that 1 second. What I can use in c++?

Can I use delay() or something else?


[from the comments]: Let me explain scenario: I have one main thread (LONG) that starts the another sub thread (SHORT), so i need to keep the execution LONG thread, so that it ends after the execution of SHORT. – Prajkata 4 mins ago

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
Prajkata
  • 65
  • 6
  • 5
    What problem are you trying to solve? A thread will execute for as long as it take to perform the operations defined by the code in the thread. – ChrisF Aug 26 '11 at 12:35
  • 1
    Your keyboard seems to be broken. I fixed the resulting errors. – sbi Aug 26 '11 at 12:37
  • Let me explain scenario: I have one main thread (LONG) that starts the another sub thread (SHORT), so i need to keep the execution LONG thread, so that it ends after the execution of SHORT. – Prajkata Aug 26 '11 at 12:39
  • Let me refer to this topic here at Stack Overflow: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Cassio Aug 26 '11 at 12:43
  • I think you should revisit the design of your application instead of using a contrived way to make the thread to last longer. Doing this way is bug prone, and usually not satisfactory. – Shlublu Aug 26 '11 at 12:45
  • 3
    @Prajkata: You should have that information as part of the actual question rather than as an entry in the comments where it might not be read by other users. – David Rodríguez - dribeas Aug 26 '11 at 12:45

2 Answers2

8

If you need to wait for a thread, then do that. Use pthread_join or the join() member function of std::thread, or the appropriate wait function for whatever mechanism you used for starting the thread.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
4

You don't want to wait for 1 second or indeed any length of time. You cannot predict how long the other thread will run.

What you want to do is to wait for the other thread to complete. All threading libraries have methods for doing this sort of synchronization. In Windows you use WaitForSingleObject, in pthreads you call pthread_join and so on.

These functions will block execution until the other thread has completed its work, exactly what you need.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490