Using Semaphores?

Hello people, having a problem to allocate a new semaphore with an initial count of 0 in this program? The finished program will have the score print out as it changes which in this case will be a couple of times a second.

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <complex>
#include <process.h>

#ifdef _WIN32
#include <tchar.h>
#include <sys/types.h>
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif

// Return the current time in milliseconds.
// (1000 milliseconds = 1 second.)
long long int get_time()
{
#ifdef _WIN32
	struct _timeb timebuffer;
	_ftime64_s(&timebuffer);
	return (timebuffer.time * 1000LL) + timebuffer.millitm;
#else
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (tv.tv_sec * 1000LL) + (tv.tv_usec / 1000LL);
#endif
}

using namespace std;

double score = 0.0;
CRITICAL_SECTION cs; // declare mutex
HANDLE changed_sem;

unsigned __stdcall addThread(void * data);

void compute_score()
{
	cout << "Score:" << score << endl;
}

#ifdef WIN32
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int argc, char *argv[])
#endif
{
	//long long int start;
	//start = get_time();	//start timing code

	HANDLE handles[10];
	
InitializeCriticalSection(&cs);
	
for(int threads = 0; threads < 10; threads++)
	{
		
		handles[threads] = (HANDLE) _beginthreadex(NULL, 0, addThread, NULL, 0, NULL);
		
	}
	WaitForMultipleObjects(10, handles, TRUE, INFINITE);
	compute_score();

	//long long int end;
	//end = get_time();	//end timing code
	//cout << "Time Taken:" << end - start << endl;

DeleteCriticalSection(&cs);	
	
	cin.get();
	cout << "Press enter to exit" << endl;
	return 0;
}

unsigned __stdcall addThread(void * data)
{	

int i = 0;
	while (i < 1) 
		{
			i++;
			EnterCriticalSection(&cs); // lock
			Sleep(500);
			score += 1.0;
			LeaveCriticalSection(&cs); // unlock
		}

	return 0;
}


Can anyone help me out please?
Last edited on
Topic archived. No new replies allowed.