Hi all,
I Just have just getting started to use intels Threading Building Blocks, but it just took some minutes before I got some problem. If I am running the code below will m_type.size() always return 0 even if i am pushing new data in a second thread:
Code:
#include <string>
#include <iostream>
#include <boost/thread.hpp>
#include "tbb/concurrent_vector.h"
class Test
{
public:
Test(tbb::concurrent_vector<std::string> & t)
//: m_type(t)
{
}
void worker()
{
std::cout << "Producing now..";
while(true)
{
if(m_type.size() < 1000)
{
m_type.push_back(std::string("Mohaha"));
std::cout << "worker: size = " << m_type.size() << std::endl;
}
}
}
void consumer()
{
std::cout << "Consuming now..";
while(true)
{
std::cout << "Consumer: size = " << m_type.size() << std::endl;
if(m_type.size())
{
std::string message = m_type.back();
std::cout << "Message: " << message << std::endl;
if(m_type.size() > 100)
{
m_type.clear();
}
}
}
}
private:
tbb::concurrent_vector<std::string> m_type;
};
int main(int argc, char** argv)
{
tbb::concurrent_vector<std::string> vec;
Test test(vec);
boost::thread thread(boost::bind(&Test::worker, test));
boost::thread thread2(boost::bind(&Test::consumer, test));
thread2.join();
thread.join();
}
But if I am making m_type to a reference (&) will it work without problems.
I know that local variables can be read into a processor cache and that is what I think happens, but how do I prevent it? And if it isn't the problem, what I am doing wrong then?
I second question:
Do any of you have any good multi threading links to share?
Thanks in advance