c# - ZeroMQ Kill Thread function -
c# - ZeroMQ Kill Thread function -
i'm creating project using zeromq. need functions start , kill thread. start function seems work fine there problems stop function.
private thread _workerthread; private object _locker = new object(); private bool _stop = false; public void start() { _workerthread = new thread(runzeromqserver); _workerthread.start(); } public void stop() { lock (_locker) { _stop = true; } _workerthread.join(); console.writeline(_workerthread.threadstate); } private void runzeromqserver() { using (var context = zmqcontext.create()) using (zmqsocket server = context.createsocket(sockettype.rep)) { /* var bindingaddress = new stringbuilder("tcp://"); bindingaddress.append(_ipaddress); bindingaddress.append(":"); bindingaddress.append(_port); server.bind(bindingaddress.tostring()); */ //server.bind("tcp://192.168.0.102:50000"); server.bind("tcp://*:12345"); while (!_stop) { string message = server.receive(encoding.unicode); if (message == null) continue; var response = processmessage(message); server.send(response, encoding.unicode); thread.sleep(100); } } }
maybe have thought stop() function, why doesn't kill thread? got hint should utilize thread.memorybarrier , volatile have no thought how should works. there processmessage() function process messages, didn't re-create don't litter :)
the problem seems you're calling blocking version of zmqsocket.receive
. while it's waiting receive message it's not processing rest of code, never hits loop condition.
the solution utilize 1 of non-blocking methods, or 1 has timeout. seek this:
string message = server.receive(encoding.unicode, timespan.frommilliseconds(100));
this should homecoming after 100ms if no message received, or before if message arrives. either way shot @ loop condition.
as _stop
flag itself...
when you're accessing variables multiple threads locking idea. in case of simple flag however, both reading , writing pretty much atomic operations. in case it's sufficient declare volatile (private volatile bool _stop = false;
) tell compiler create sure reads current value each time tell to.
c# multithreading zeromq
Comments
Post a Comment