Ihr Beispiel schlägt vor, dass alles, was Sie in Ihren Threads tun möchten, eine Operation auf einer int-Variablen ist. Wenn das wirklich der Fall ist, wie andere darauf hingewiesen haben, ist std::atomic
wahrscheinlich der einfachste Weg, es zu implementieren.
#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;
}
jedoch gleichzeitig in mehreren Threads zu schützen ausgeführt kompliziertere Operationen aus wird, sollten Sie std::lock_guard
verwenden. Es verwendet das RAII-Prinzip (Resource Acquisition is Initialization), um einen Mutex für seine Lebenszeit zu sperren.
#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
Basierend auf Ihre Kommentare hier ein anderes Beispiel ist:
#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;
}
Wenn Sie 'pthread's verwenden, dann können Sie' pthread_mutex_lock' verwenden und 'pthread_mutex_unlock' –
Der einfachste Weg, wenn Sie C++ 11 haben, ist 'std :: atomic x;'. –