Thread safe spinning with Mutex and boost::threads
I have several threads accessing the same function. To guarantee safe spinning, which means none of the threads calls ros::spinOnce()
at the same time I used a regular mutex. So if the threads wants to spin he has to lock it before, so in case he gets interrupted another thread cannot spin meanwhile, until the locking thread gets cpu-time again and releases the lock.
Is this approach good/bad Idea?
boost::mutex safespinmutex;
#include <boost/algorithm/string.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
boost::mutex mtx_spin; //shared by publisher threads
//thread safe regular mutex spin
mtx_spin.lock();
ros::spinOnce();
mtx_spin.unlock();
loop_rate.sleep();
}
It is similar to c11 mutex, just here I use c98 syntax with boost::threads and boost::mutex
:)
Edit more Info
I spawn a maximum of 13 threads each dedicated to publishing, which is a lot, but I dont see any problem: The call to lock()
blocks the thread if another thread is inside the spinOnce()
but yet not finished. Once done this thread unlocks the mutex and unblocks the waiting thread. voila or am I conceptually wrong?
This is how I start the publishing threads
boost::thread tpool[14]; //thread pool
int pool = 0;
for (unsigned i=0; i<13; i++){
if(rate_eff[i]!=0) {
tpool[pool++] = boost::thread(publisher,(i+1), use_def);
}
}
cout<<" publishing on "<<(pool-1)<<" topics:"<<endl;
Benchmark
To confirm what said above I spawned 9 topics each managed by their own publisher thread. One Incoming thread sorts stuff into the internal vectors rate(100Hz) and the 9 publisher threads read it with 1000Hz rate
and push it onto their topic. Does it run safe: Yes.
I am glad about suggestions and improvements but please fortify your statement.
In case you want to have a look at the complete code here.