boost::threadpool without locking

I have some basic question. Please don't comment about class desing its just like this so i could easely try to explain what i want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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 your time.
Last edited on
you need locking only when two or more threads access the same variable (read/write).

In you case Bar is not a variable but the environment.
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?

Thank you for your time.
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.
Last edited on

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).
Last edited on
OK. Thanks everybody.
atomic variables are part of C++11 @ rapidcoder.
Though I'm not sure how widely they're supported.
Topic archived. No new replies allowed.