c++multithreadingboostmutexscoped-lock

C++ boost thread and mutex


I just started on boost. I would like to ask if my code uses mutex well. To test it I wrote code which counts sum of numbers 1 to n. Silly way to count it but I used n threads... just to try mutex...

#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>

#define NUMBER 10

boost::mutex mutex;
unsigned long long sum = 0;

class counter
{
public:
    counter() : count(0) { }

    unsigned long long increment() 
    {
        return ++count;
    }

private:
     unsigned long long count;
};

counter c;

void count()
{
    boost::mutex::scoped_lock scoped_lock(mutex);
    unsigned long long i = c.increment();
    sum += i;
    std::cout << "i=" << i << "\tsum=" << sum << std::endl;
}

int main(int, char*[])
{
    boost::thread_group thrds;
    for (int i=0; i < NUMBER; ++i)
    {
        thrds.create_thread(&count);
    }
    thrds.join_all();

    system("pause");
    return 0;
}

Results look good and without mutex looks bad, so I think I used it correctly, but just want to ask if everything is ok. Thanks for any advice; I hope it'll be helpful for me and others.


Solution

  • Looks good, though i would not use global variables, but that's not what your example is about...

    You should also lock cout if you use it elsewhere because that can produce real non-sense if two threads are working on it at the same time.