java - What is the correct way to pass data to a running thread -


in cases when create thread can prepare data beforehand , pass constructor or method.

however in cases open socket connection typically have thread created wish tell perform action.

basic idea:

c#  private thread _mythread = new thread(mymethod); this._mythread.start(param);     java  private thread _mythread = new thread(new myrunnableclass(param)); this._mythread.start();  what? 

so correct way pass data running thread in c# , java?

one way pass data running thread implementing message queues. thread wants tell listening thread add item queue of listening thread. listening thread reads thread in blocking fashion. causing wait when there no actions perform. whenever thread puts message in queue fetch message, depending on item , it's content can it.

this java / pseudo code:

class listener {    private queue queue;    public sendmessage(message m)    {      // executed in calling thread.      // locking done either in function or in add below      // depending on queue implementation.      synchronize(this.queue)       {         this.queue.put(m);      }    }     public loop()    {      // function should called listener thread.      while(true)       {         message m = this.queue.take();         doaction(m);      }    }     public doaction(message m)    {       if (m stopmessage)       {         ...       }    } } 

and caller:

class caller {   private listener listener;    letitstop()   {      listener.sendmessage(new stopmessage());   } } 

of course, there lot of best practices when programming paralllel/concurrent code. example, instead of while(true) should @ least add field run :: bool can set false when receive stopmessage. depending on language in want implement have other primitives , behaviour deal with.

in java example might want use java.util.concurrent package keep things simple you.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -