In thread pool, threads are reused to avoid thread creation and destruction. When the thread pool reuses a thread, it does not clear the data in thread local storage. Hence, when a method examines thread local storage, the values it finds are left over from an earlier use of the thread pool thread.
Function local variables are local to function and not to threads. But when i created a thread pool using boost::asio::thread_pool, the memory for local variables created inside function share the same memory for the same thread.
Hence, I have few questions...
- Are function local variables stored inside thread local storage. And is it because of that i am getting same memory for the same threads?
- The same question for function parameters which are passed by value ?
- Is there any way to clear the thread local storage before reusing the threads?
Program
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/asio/thread_pool.hpp>
#include <BoostThreading/UtilBoost.hpp>
#include <iostream>
boost::mutex mutex;
void my_task(int g)
{
boost::lock_guard<boost::mutex> lock(mutex);
int i=0;
i++;
std::cout<<boost::this_thread::get_id()<<" "<<&i<<" "<<i<<" "<<&g<<" "<<g<<"\n";
SleepMs(30);
}
int main()
{
boost::asio::thread_pool pool(4);
for(int i=0;i<10;i++)
boost::asio::post(pool, boost::bind(my_task,i));
pool.join();
}
First is the thread id, second is the address for variable i created inside the function and third address is the address for variable g passed to my_task by pass by value.