Multithreading Test Programm

hey There...

i had a small break^^...
and now im trying on multithreading and something is going really wrong^^...

my problme is, that i want to make a prog , that will count keyboard-hits with 1 thread and the other counts to the final 10th hit.

I tryed with kbhit()... but somehow it does stop instantly when hitting any key -.-'

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
#include <iostream>
#include <process.h>
#include <conio.h>

using namespace std;

short int counter1 = 0;
long counter2 = 0;

void count(void*);

void main()
{
	_beginthread(count,NULL,NULL);

	while(counter1 < 10)
	{
		counter2++;
	}

	cout << "\n" << counter2 << "\n";
	while(kbhit() != 'q')
	{
	}

}

void count(void*)
{
	while(counter1 < 10)
	{
		getch();
		
		counter1++;
		cout << "Counted\n";
	}
	
	cout << "\nThread closed!\n\n";
	_endthread();

}




got it...
Last edited on
You need to eat the char that kbhit sees. So put a _getch() just before counter1++;
kbhit() will return a positive number each time it is called after you press any key. So in your loop in count() it will loop around returning 0 until you press a key when it will start returning a positive number. While you dont press a key the loop in main() loops around very fast giving the processor a hard time because counter1 is 0 until you press a key.

To fix this you should call getch() when kbhit() returns positive to clear the buffer before the next call to kbhit(), but the main thread will still loop around crazy until you have pressed 10 times and then counter2 will be some large (or wrapped) number.

Dont know why you create a thread or what you are really trying to do.

I just wanted to test something with threads and a kbhit()-loop.

It was nothing serious as u may have seen^^...

The problem now is, that i littered my c++-book due to an contretemps:(...

And its from 1999 so i cant buy it again :(...
Topic archived. No new replies allowed.