二话不说,直接上代码了。
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
volatile int shared_value = 0;
volatile int running_count = 1000;
mutex mtx;
void change_value (int n)
{
for (int i = 0; i < n; i++)
{
if (mtx.try_lock())
{
shared_value++;
mtx.unlock();
}
}
running_count--;
}
int main ()
{
thread t[100];
for (int i = 0; i < 100; i++)
{
t[i] = thread (change_value, 1000);
}
for (int i = 0; i < 100; i++)
{
t[i].join();
}
cout << shared_value << endl;
cout << running_count << endl;
return 0;
}