Hello, beginner to C++ and code in general here.
I have been teaching myself how to code for about the last month (using on-line tutorials), and am in the process of creating a simple text-based RPG using Microsoft Visual Studio 2010.
Things have been going good and my understanding of classes and pointers is growing, but I have run into a road-block.
I am wanting to create two combat loops for my RPG for two different classes (the attacker and the attacked) that will execute simultaneously. I understand that multi-threading is the key, and am trying to get a better understanding of it, but the MSDN website has left me with a very foggy understanding of multi-threading.
Which brings me to my problem.
From looking at the MSDN website and their pages on multi-threading, i created a basic program that will set two different threads to increase a global integer and then use std::cout to print it to the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
// multi-threading_practice.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <iostream>
#include <string>
//The function getrandom returns a random number between
//min and max, which must be in integer range.
#define getrandom(min,max)(SHORT)((rand()%(int)(((max)+1)-\(min)))+(min))
using namespace std;
HANDLE hRunMutex; //"Keep Running" mutex
HANDLE hPrintMutex; //"Integer printed" mutex
int ThreadNr; //number of threads started
int x;
void printNumber(void* pInt)
{
int i=(int)pInt;
while(i<100)
{
WaitForSingleObject(hPrintMutex,INFINITE);
++i;
cout<<i<<endl;
ReleaseMutex(hPrintMutex);
}
}
void printNumberDouble(void* pInt)
{
int i=(int)pInt;
while(i<100)
{
WaitForSingleObject(hPrintMutex,INFINITE);
++i;
++i;
cout<<i<<endl;
ReleaseMutex(hPrintMutex);
}
}
int main()
{
x=0;
_beginthread(printNumber,0,&x);
_beginthread(printNumberDouble,0,&x);
return 0;
}
|
The above code will compile fine, but when ran, a console is created, and all that is printed is the "press any key to continue" after the main() function executes.
From my understanding, this should have worked, but then my understanding of multi-threading is very, very foggy.
Any clarification would be very much appreciated.