简体   繁体   中英

Can you throw an exception to the parent thread

I am supposed to implement a primitive multithreaded server that starts a new thread for each connection.

It should be possible that one of the thread gets the message to shut down the server.

Is it possible to notify the parent thread from one of the child threads to stop accepting new connections and shut the server down?

As you probably know, you can have shared variable over multiple threads.

You could use boolean variable, let's say exceptionOccured or serverShutdown , which would default to false and in exception handlers in each thread you set this variable to true.

In main thread, you will monitor values of this variable and do necessary work in case when this variable becomes true (ie stop all threads, etc.).

In order to implement this you must first read about volatile keyword

There are several ways for inter thread communication :

  1. You can keep a shared state (root of evils in multithreading) and update it and let the main thread check that state several times (use volatile or barriers)
  2. While creating worker thread you can pass an instance of main thread and if any thread at any point wants to stop the main thread it can call a method on main thread to stop accepting further requests (more optimized than previous solution).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM