Recent Changes
Search:

:: Personal ::

E

Main / CoursesAAMultiThreadingWindows

Very simple c++ program that demonstrates how to create and execute threads in Windows. I compile and run as a win32 console application in Visual C++ Express 2010.

#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <iostream>

using namespace std;

// Stores the arguments passed around in the code below.
struct Args {
  HANDLE mutex;
  int thread_num;
  double start;
  double end;
  double sum;
  Args(HANDLE _mutex, int _thread_num, double _start, double _end)
    : mutex(_mutex), thread_num(_thread_num), start(_start), end(_end), sum(0) { 
  }
};

// Adds up the numbers (increments of 1) from start to end.
void GetSum(Args* args) {
  // We print the following message under mutex lock so it is not interrupted.
  WaitForSingleObject(args->mutex, INFINITE);
  cout << "Starting thread: " << args->thread_num << " sum range "
       << args->start << " to " << args->end << endl;
  ReleaseMutex(args->mutex);

  for (double i = args->start; i < args->end; i++) {
    // Print out our progress. We don't bother mutex locking here.
    if (fmod(i, 1e7) < 0.1) { 
      cout << "T(" << args->thread_num << ") at: " << i << endl;
    }
    args->sum += i;
  }
}

void RunSingleThread(HANDLE mutex, double max) {
  Args args0(mutex, 0, 0, max);
  GetSum(&args0);
  cout << "Single Threaded - Sum: " << args0.sum << endl << endl;
}

void Run2Threads(HANDLE mutex, double max) {
  HANDLE thread[2];
  Args args0(mutex, 0, 0, max / 2);
  Args args1(mutex, 1, max / 2 + 1, max);

  // Create and start two separate threads to compute the sums.
  thread[0] = (HANDLE)_beginthread((void(*)(void*))GetSum, 0, (void*)&args0);
  thread[1] = (HANDLE)_beginthread((void(*)(void*))GetSum, 0, (void*)&args1);

  // This waits until both threads are done.
  WaitForMultipleObjects(2, thread, TRUE, INFINITE);

  // Total the partial sums from the two threads and output the result.
  cout << "Multithreaded - Sum: " << args0.sum + args1.sum << endl << endl;
}

int _tmain(int argc, _TCHAR* argv[]) {
  double max = 3e8;

  HANDLE mutex = CreateMutex(NULL, FALSE, NULL);
  DWORD start = GetTickCount();

  RunSingleThread(mutex, max);
  DWORD end_single = GetTickCount();

  Run2Threads(mutex, max);
  DWORD end_dual = GetTickCount();

  cout << end_single - start << " ms (single thread) " << endl
       << end_dual - end_single << " ms (dual threads) " << endl;
  return 0;
}