あなたの例では、あなたのスレッドでやりたいことは、int変数の操作であることが示唆されています。それが本当の場合は、他の人が指摘しているように、std::atomic
がおそらくそれを実装する最も簡単な方法でしょう。
#include <thread>
#include <atomic>
#include <iostream>
std::atomic<int> x = 0;
void increment()
{
for(int i = 0; i < 10000000; ++i)
{
++x;
}
}
int main()
{
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << x;
}
しかし、同時に複数のスレッドで実行されることから、より複雑な操作を保護するために、あなたはstd::lock_guard
を使用する必要があります。 RAII(リソース獲得は初期化です)原則を使用して、その存続期間中にmutexをロックします。
#include <thread>
#include <mutex>
#include <iostream>
int x = 0;
std::mutex mtx;
void increment()
{
for (int i = 0; i < 10000000; i++)
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
++x;
// mtx is automatically released when lock
// goes out of scope -> RAII
}
}
int main()
{
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << x;
}
ここにあなたのコメントに基づいてEDIT
は別の例である:
#include <thread>
#include <mutex>
#include <iostream>
class Foo
{
public:
void increment()
{
for (int i = 0; i < 10000000; ++i)
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
++x;
// mtx is automatically released when lock
// goes out of scope -> RAII
}
}
void decrement()
{
for (int i = 0; i < 10000000; ++i)
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
--x;
// mtx is automatically released when lock
// goes out of scope -> RAII
}
}
static int x;
static std::mutex mtx;
};
int Foo::x = 0;
std::mutex Foo::mtx;
int main()
{
std::thread t1(&Foo::increment, Foo());
std::thread t2(&Foo::decrement, Foo());
t1.join();
t2.join();
std::cout << Foo::x;
}
あなたは 'pthread'sを使用している場合は、' pthread_mutex_lock'と 'pthread_mutex_unlock' –
を使用することができます最も簡単な方法は、C++ 11をお持ちの場合は、 'std :: atomic x;'です。 –