开发者

C++ UNIX: Threading: Make Main-Thread wait or sleep until processing is over - main-thread doesnt know pthread_t refrences

开发者 https://www.devze.com 2023-04-06 07:14 出处:网络
sc->start_server runs an endless loop in which a MyClass processing method is invoked in a thread. How can i replace the while(true) statement in main so that my program waits for all threads t开发者_

sc->start_server runs an endless loop in which a MyClass processing method is invoked in a thread. How can i replace the while(true) statement in main so that my program waits for all threads t开发者_JAVA百科o terminate?

EDIT: pthreads-lib is used and main() does not know the pthread_t references

THX

 int main(int argc, char** argv)
    {

            SocketCommunication * sc = SocketCommunication::get_menu();  //Singleton

            MyClass yay;       
            short port = 6644;

            sc->start_server(port, &yay);

            while(true);

        return 0;
    }


The usual way (in pthreads, at least) is:

  1. You have several pthread_t references to running threads.
  2. Instead of your while loop at the end, you wait for all of them to finish with something similar to pthread_join(threadX, NULL);, for all the threads.

In your case, I don't see any API to get the threads, but once you get hold of the threads running (maybe asking sc in some way), the code would be similar.

EDIT:

If you just want to wait for a condition, it is easy with condition variables. Supposing you have available these:

pthread_mutex_t end_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  condition_var = PTHREAD_COND_INITIALIZER;
bool all_threads_done = false; // Signals that all the threads are finalized

Then, in your main() you can wait for it with:

pthread_mutex_lock( &end_mutex );
while (!all_threads_done) 
    pthread_cond_wait( &condition_var, &end_mutex );

The wait will release the mutex while waiting. Then, on each thread, you have to have the following:

// Do whatever the thread has to do...
// ...
// and then, at the end...
pthread_mutex_lock( &end_mutex );
if (no_more_threads()) // You have to figure this thing out to ensure no more threads
    all_threads_done = true;
pthread_cond_signal( &condition_var );
pthread_mutex_unlock( &end_mutex );

Note, finally, that, even when you're doing a while, it is not a busy waiting, as most of the time the main thread is waiting in pthread_cond_wait, and is awakened just when any of the threads ends.


Use join on any thread you want to wait.

0

精彩评论

暂无评论...
验证码 换一张
取 消