Mike Whiskey Mike Whiskey - 2 years ago 268
C Question

C/C++ multithreded code example inconsistent data

Would any of you have idea of some code in c/c++ which would
have few threads running operations on a variable or array of variables which would eventually lead to creating inconsistent data.
I need it for school project to prove that inconsistency in data can be created by running threads which are not synchronized.

Answer Source

The following code will produce inconsistent results:

#include <iostream>       // std::cout
#include <thread>         // std::thread

void printFirst() 
  std::cout << "first\n";

void printSecond() 
  std::cout << "second\n";

int main() 
  std::thread firstThread (printFirst);     // spawn new thread that calls printFirst()
  std::thread secondThread(printSecond);    // spawn new thread that calls printSecond()

  // Threads are run independently:

  // Threads are synchronized:
  // firstThread.join();                // pauses until first finishes
  // secondThread.join();               // pauses until second finishes

  return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download