multithreading - How to avoid blocking thread during some heavy processing in c++? -


i'm beginner of c++ multi threading program. created dummy code question. hoge class communication class connected socket , assume hoge::update() data receiving class via socket. , if specific data has arrived, hoge instance pass data fuga instance specifigc processing.

so questions are,

  1. i don't want block hoge::update(). after storing data, don't want use th_process_data.join(). there better solution this?
  2. after processing data in thread, how return processed data hoge instance. callback class solution?

hoge.cc

fuga fuga; hoge::update() {   while(true) {     if(check_something()) {       auto data = get_data();       fuga.push_data(data);     }   } }  hoge::on_received(const data& data) {   std::cout << "received: " << data.id << std::endl;   // something... } 

fuga.cc

std::vector<data> data_list; std::mutex mtx;  fuga::push_data(const data& data) {   {     std::lock_guard<std::mutex> lock(mtx);     data_list.push_back(data);   }   std::thread th_process_data([&]{ do_processing(); });   // q1. don't want block thread hoge::update() }  fuga::do_processing() {   data data;   {     std::lock_guard<std::mutex> lock(mtx);     data = data_list.pop();   }    // heavy task data...   std::this_thread::sleep_for(std::chrono::seconds(3));     // q2. how pass processed data hoge::on_received(const data& data) } 

part of q not clear me seems open ended many possibilites. 2 queries objective, hence trying answer recent experience sockets.

"1. don't want block hoge::update(). after storing data, don't want use th_process_data.join(). there better solution this?"

in such case, may do:

th_process_data.detach(); 

this save blocking on .join(). may use std::future , std::promise combo if design allows. more information can found in this post.

"2. after processing data in thread, how return processed data hoge instance. callback class solution?"

i don't see big deal in calling hoge::on_received() method , pass data. thread still th_process_data only. if worried providing time slicing , using sleep_for() method it, may std::yield alternative.


according current design have put 2 std::mutex in 2 methods. feel, it's not required.
also, remember creating thread every time fuga::push_data() invoked. if method invoked , don't want load cpu expense of multiple threads creation, better create single thread once , wait in data received. require change of design.