class Foo
{
X data[3]; // read only from threads
bool flag1;
bool flag2;
};
class Bar
{
threadpool::pool tpool;
typedef std::shared_ptr<Foo> tFoo;
vector<tFoo> vFoo1;
vector<tFoo> vFoo2;
vector<tFoo> vFoo3;
.....
};
Bar::Bar(...) : tpool(2) {...}
void Bar::addStuff(X data, bool b, bool c)
{
tFoo f = tFoo(new Foo(data));
vFoo1.push_back(f);
if(b)
vFoo2.push_back(f);
if(b && c)
vFoo3.push_back(f);
}
void Bar::update()
{
auto fun1 = bind(&Bar::job1, this);
auto fun2 = bind(&Bar::job2, this);
auto fun3 = bind(&Bar::job3, this);
tpool.schedule(fun1);
tpool.schedule(fun2);
tpool.schedule(fun3);
tpool.wait();
.... back to single thread
}
void Bar::job1()
{
// some work with vFoo1
}
void Bar::job2()
{
// some work with vFoo2
}
void Bar::job3()
{
// some work with vFoo3
}
Ok, i got couple of "different" vectors witch holds pointers that point to same data. Job1 does read-only on Foo objects and only sets Foo flag1, Job2 -||- sets flag2 and Job3 just sorts its vector.
I don't need any locking mechanism here?
Thank you for helping me, but i am not clear what you say.
In my example above, 2 threads could access same data but it will be read-only operation, in this case is it ok?
if the variable is never changed it is of course no problem and no lock is required
if there's a single instruction (such as i = 2 where i is int) read and write you might not need a lock.
you need a lock if there's a combination of read/write (within a thread). You certainly need a lock when the vector is changed while another thread has any kind of access to it.
if there's a single instruction (such as i = 2 where i is int) read and write you might not need a lock
Never, ever rely on this. There are so many things that can break this assumption, that on most systems it does not hold. Use atomic integers in that case (not sure if STL has them at last, but Java has had them for more than 5 8 years now).