-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.cpp
More file actions
83 lines (59 loc) · 1.87 KB
/
threads.cpp
File metadata and controls
83 lines (59 loc) · 1.87 KB
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
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "structures.h"
#include "file.h"
#include "commands.h"
// declarations
DWORD Thread_Loop(void *param);
// global CSs
CRITICAL_SECTION CS_Threads;
// global linked lists
ThreadInfo *thread_list = NULL;
// global variables
long thread_cur = 0;
long thread_active = 0;
// uses an external (sent to client) thread ID to find an internal thread structure
ThreadInfo *thread_search(int id, unsigned long tid) {
ThreadInfo *tptr = NULL;
ThreadInfo *ret = NULL;
EnterCriticalSection(&CS_Threads);
for (tptr = thread_list; tptr != NULL; tptr = tptr->next) {
//if (((id && tptr->thread_id == id) ||
if ((id == tptr->thread_id) || (tid && tptr->tid == tid)) {
EnterCriticalSection(&tptr->CS);
ret = tptr;
break;
}
}
LeaveCriticalSection(&CS_Threads);
return ret;
}
// create a new thread and initialize its structure
ThreadInfo *thread_new() {
// create thread here.. return the info into tptr...
HANDLE thread_handle = NULL;
int thread_created = 0;
unsigned long tid = 0;
ThreadInfo *tptr = NULL;
// alloc space for the new thread structure
if ((tptr = (ThreadInfo *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ThreadInfo))) == NULL)
return NULL;
// ensure we can create the thread
if ((thread_handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Thread_Loop, (void *)NULL, 0, &tid)) == NULL)
return NULL;
thread_created = thread_handle != NULL;
EnterCriticalSection(&CS_Threads);
InitializeCriticalSection(&tptr->CS);
InitializeCriticalSection(&tptr->QCS);
EnterCriticalSection(&tptr->CS);
// setup structure
tptr->thread_id = InterlockedExchangeAdd(&thread_cur, 1);
tptr->tid = tid;
tptr->handle = thread_handle;
// add to global thread list
tptr->next = thread_list;
thread_list = tptr;
LeaveCriticalSection(&tptr->CS);
LeaveCriticalSection(&CS_Threads);
return tptr;
}