150
edits
Changes
→Code for Intel Inspector
return 0;
}
</syntaxhighlight>
== Thread Race Conditions ==
<syntaxhighlight lang="cpp" line='line'>
#include <iostream>
#include <thread>
#include <vector>
// Counter Object
class Counter;
int runCounter();
int main()
{
int val = 0;
// Runs the counter 1000 times and has 10 threads iterate it by 1000 each, needs to reach 10000 in total
for (int k = 0; k < 1000; k++)
{
if ((val = runCounter()) != 10000)
{
std::cout << "Error at count number = " << k << " Counter Value = " << val << std::endl;
}
}
return 0;
}
class Counter
{
//counter
int count;
public:
Counter() {
count = 0;
}
int getCounter() {
return count;
}
void add(int num) {
for (int i = 0; i < num; ++i)
{
// lock should be applied here
count++;
}
}
};
int runCounter()
{
Counter counter;
//creates a vector of threads
//Creates 10 threads gives it a reference to the counter object, resulting in 1000 count++ calss from each thread
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.push_back(std::thread(&Counter::add, &counter, 1000));
}
//joins threads
for (int i = 0; i < threads.size(); i++)
{
threads.at(i).join();
}
return counter.getCounter();
}
</syntaxhighlight>