On Thursday, December 13, 2012 12:31:05 AM UTC+3:30, Luca Risolia wrote:
On 12/12/2012 14:16, Saeed Amrollahi wrote:
Hi
I have the following very simple multi-thread program:
#include <thread>
#include <mutex>
int var = 0;
void incr()
{
std::mutex m;
m.lock();
var++;
m.unlock();
}
int main()
{
std::thread t{incr};
std::mutex m;
m.lock();
++var;
m.unlock();
t.join();
return 0;
}
This is really simple program, and I think,
I made a mutual exclusion, when two threads
are writing shared variable (var).
In your simple case you can get rid of the mutex by declaring the shared
variable as std::atomic_int.
Anyway, if really want to protect shared data with *one* mutex, wrap it
with a std::lock_guard or a std::unique_lock instead of using the
mutex directly, as others have said. A std::lock_guard is faster and can
be used in a local {} block in your main() as well:
int main() {
//...
{
std::lock_guard<std::mutex> lg(m);
++var;
}
t.join();
//...
}
--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
Thank you.