0

I have a code where I call some GET and POST CURL functions in a loop. I want to call it and the result do not matter to me cause inside the function it's saves the result in a log file. The speed is crucial so I am detaching this functions like the code bellow:

for(;;){
    
  // other codes ///
  std::thread httpthread = std::thread([&]() {


    GETPOSTEvents GETEvent;
    string LogPath = logPathforerror;
                                                                    
    GETEvent.sendHttpEvent(quantity3_HTTPEvent, LogPath);

  });

  if (httpthread.joinable()) {
     httpthread.detach();
  }
    
  std::thread httpthread2 = std::thread([&]() {
        
    GETPOSTEvents GETEvent;
    string LogPath = logPathforerror;
                                                                           
    GETEvent.sendHttpEvent(quantity3_HTTPEvent2, LogPath);
        
  });
        
  if (httpthread2.joinable()) {
    httpthread2.detach();
  }
    
    
 // other codes ///

}

My question: is this safe? Is there any problem if the detached function do not ends before the loop?

Thanks!

  • 1
    There is insufficient information in the question to authoritatively answer whether this is "safe" or not. An authoritative answer will need to know exactly how all the objects that get captured by reference, in both closures, get created and when they get destroyed. – Sam Varshavchik Apr 12 '22 at 15:46
  • 1
    Checking `joinable` before calling `detatch` is an anti-pattern. If you actually need to check because it might not be joinable, than you need to synchronize that state or you have a race condition. The thread may become non-joinable after calling `joinable()` but before calling `detach()`. And if you are sure that it will always be joinable, then calling `joinable()` has no purpose. But in general using `detatch()` is almost always a sign of a design error and the function should be avoided. – François Andrieux Apr 12 '22 at 15:49
  • Creating threads in a loop also might be a bit of an anti-pattern. Have you considered using a [_thread pool_](https://livebook.manning.com/book/c-plus-plus-concurrency-in-action/chapter-9/) instead? Unfortunately, the `std` library _still_ doesn't have one. But see answers to [this question](https://stackoverflow.com/q/15752659/801894) for alternatives. – Solomon Slow Apr 12 '22 at 16:14
  • The loop is infinite, so how could the loop end before the threads? – user253751 Apr 12 '22 at 16:22
  • And the thread is always joinable. A thread is joinable before you join or detach it - that's what joinable means in C++ – user253751 Apr 12 '22 at 16:22
  • I was trying to use boost::asio::thread_pool but use the pool.join() every iteration really slowdown the application. While detach() uses 1 millisecond.. join uses 100 milliseconds because need to wait GET request. Any idea on how to speed up with thread pool? – Everton Manso Apr 12 '22 at 18:52

0 Answers0