2

Reading that spinlock and other multitasking stuff, I faced to this code:

#include <boost/range/algorithm.hpp>
#include <boost/atomic.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <vector>

class SpinLock
{
    boost::atomic_flag flag;
public:
    void lock()
    {
        while( flag.test_and_set(boost::memory_order_acquire) )
            ;
    }
    bool try_lock()
    {
        return !flag.test_and_set(boost::memory_order_acquire);
    }
    void unlock()
    {
        flag.clear(boost::memory_order_release);
    }
};

int main()
{
    using namespace std; using namespace boost;

    SpinLock lock;
    vector<thread> v;
    for(auto i = 0; i!=4; ++i)
        v.emplace_back([&lock, i]
        {
            for(auto j = 0; j!=16; ++j)
            {
                this_thread::yield();
                lock_guard<SpinLock> x(lock);
                cout << "Hello from " << i << flush << "\tj = " << j << endl;
            }
        });
    for(auto &t: v)
        t.join();
}

Could you explain why for has only one parameter?

And what that colon operator does?

And what is that t object?

Qeeet
  • 303
  • 3
  • 13

4 Answers4

3

It's range-based for. t has type std::thread&.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
2

It's a range-based for loop. These were introduced with C++11. You are iterating over a container.

Its syntax is:

for ( range_declaration : range_expression ) loop_statement 

The for loop is executed from the beginning of the container to the end.

Laura Maftei
  • 1,863
  • 1
  • 15
  • 25
1

Example:

int  an_array[]={1,2,3,5,6,56,34,65,3,234};
for(int a : an_array)
   cout << a;

this for loop is equivalent to:

for(int index = 0; index < sizeof(an_array) / sizeof(an_array[0]) /*10*/; ++index)
   cout << an_array[index];

The supporting compilers do understand what vector is, if used against a range-based for loop, and they call begin and end for the container. Therefore, the last loop is same as:

for(vector<thread>::itereator t =  v.begin(); t != v.end(); ++t)
        t->join(); // Or. (*t).join()
Ajay
  • 18,086
  • 12
  • 59
  • 105
0

range-based for loop, you dont need to know size, it means for all t's in container v do something (join in this case). somewhat diffrent from traditional for loop

Ali Kazmi
  • 1,460
  • 9
  • 22