Login Page - Create Account

Support Board


Date/Time: Wed, 27 Nov 2024 16:47:19 +0000



Post From: C++ threads inside a ACSIL study?

[2023-02-09 20:35:22]
User133994 - Posts: 80
User431178 and ondafringe,

Thanks so much for your insight.

no more crashes, yeah!!

Correct implementation:

1) Add these global variables (so they never go out of scope):

boost::asio::io_service io_service;
boost::asio::io_service::work work(io_service);
std::vector<std::thread> threads;

2) Updated code block I originally sent (only 1 persistent variable, need to re-consider adding globals as persistent variables in the future):

s11n_example::client* pClient = reinterpret_cast<s11n_example::client*>(sc.GetPersistentPointer(pClientKeys[0]));

if (pClient == nullptr){
try
{

sc.SetPersistentPointer(pClientKeys[0], new s11n_example::client(io_service, host, port, sc));

auto count = std::thread::hardware_concurrency() * 2;
if (count > 2) count = 2; //debugging shows an excepetion after 2? (on R&D machine); count = 8 while debugging prior to me adding this line

for(int n = 0; n < count; ++n)
{
  threads.emplace_back([&]
{
io_service.run();
};
}
.
.
.

3) Add these statements on uninitialization (i.e. LastCallToFunction):

if (sc.LastCallToFunction){
if (pClient == nullptr)
   //do nothing
   int a = 1;
else
{
io_service.stop(); // That's OK, io_context::stop is thread-safe
// work.reset(); compiler can't find?

for(auto& thread : threads)
{
if(thread.joinable())
{
  thread.join();
}
}
delete pClient;
}
}

So yes, I didn't have a method to properly shut down such threads; and, this is just the beginning framework, I have more things to iron out. But this works. Thanks again.