-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.c
506 lines (423 loc) · 11.9 KB
/
thread.c
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*
* Main Author : Jeffrey Robinson
* Contributing Authors : Gabriel Loewen
* Barely Authors : John C. Lusth
* Last Modified : May 4, 2014
*
* If multithreading is enabled a thread is started
* if all other threads are busy. Otherwise the work
* requested goes on the work queue. If maximum number
* of threads have been requested then all work goes
* on the work queue.
*
* If multithreading is not enabled then each thread
* is run serially.
*
* TODO : Make the main thread do work instead of busy
* waiting at the end of scam.c
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sched.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include "scam.h"
#include "cell.h"
#include "pp.h"
#include "env.h"
#include "util.h"
#include "eval.h"
#include "types.h"
#include "thread.h"
/* Threads */
pthread_t *Thread;
/* Thread management */
int CreatedThreads = 0;
int WorkingThreads = 0;
int ScamThreadID = 0;
int QueueCount = 0;
/* Lock and Unlock */
pthread_key_t key;
pthread_mutex_t mutex,p_mutex,t_mutex,u_mutex;
/* Deadlock Detection*/
int *P_REQ;
int *P_P_REQ;
int *T_P_REQ;
/* Internal function for pthread */
static void *InternalThread(void *);
/* Work queue for threads */
THREAD_ARGS ThreadQueue[MAX_THREADS];
int QueueFront = 0;
int QueueBack = 0;
/*
* threadingInit - Initializes all thread specific data-structures, mutexs, and
* thread conditionals.
*/
void
threadingInit()
{
pthread_key_create(&key,NULL);
/* Thread handles */
Thread = malloc(sizeof(pthread_t) * MAX_THREADS);
/* Deadlock detection */
P_REQ = malloc(sizeof(int) * MAX_THREADS);
P_P_REQ = malloc(sizeof(int) * MAX_THREADS);
T_P_REQ = malloc(sizeof(int) * MAX_THREADS);
/* Thread mutexes */
pthread_mutex_init(&mutex, NULL); /* Global Mutex */
pthread_mutex_init(&p_mutex, NULL); /* Printing Mutex*/
pthread_mutex_init(&t_mutex, NULL); /* Memory Mutex */
pthread_mutex_init(&u_mutex, NULL); /* User Mutex */
/* Initialize all threading data-structures */
int i = 0;
while(i < MAX_THREADS)
{
P_REQ[i] = NO_INTEREST;
P_P_REQ[i] = NO_INTEREST;
T_P_REQ[i] = NO_INTEREST;
ThreadQueue[i].env = 0;
ThreadQueue[i].expr = 0;
ThreadQueue[i].tid = -1;
/* Default each thread */
Thread[i] = 0; //was Thread[i] = -1;
i++;
}
Thread[ScamThreadID] = pthread_self();
int *tid = malloc(sizeof(int));
*tid = ScamThreadID;
pthread_setspecific(key,tid);
CreatedThreads = 1;
WorkingThreads = 1;
}
/*
* threadingShutdown - Cleans up and releases threading resources.
*/
void
threadingShutdown()
{
free(pthread_getspecific(key));
pthread_key_delete(key);
/* Deadlock detection */
free(P_REQ);
free(P_P_REQ);
free(T_P_REQ);
/* Thread handles */
free(Thread);
/* Thread mutexes */
pthread_mutex_destroy(&mutex); /* Global Mutex */
pthread_mutex_destroy(&p_mutex); /* Printing Mutex*/
pthread_mutex_destroy(&t_mutex); /* Memory Mutex */
ScamThreadID = 0;
CreatedThreads = 0;
WorkingThreads = 0;
}
/*
* lock - Implements semaphore lock functionality. System only
* provides a single semaphore for users.
*
* @args - Ignored
*
*/
int
lock(int args)
{
if(DebugMutex)
{
P_P();
printf("Thread %d is acquiring...\n",THREAD_ID);
P_V();
}
// Remove from working group in case of garbage collection
P();
--WorkingThreads;
V();
int ret = 0;
do{
P();
if(GlobalLock == 0)
{
ret = 1;
GlobalLock = 1;
}
V();
usleep(10);
} while(ret == 0);
// Add back to working set for garbage collection
P();
++WorkingThreads;
V();
if(DebugMutex)
{
P_P();
printf("Thread %d has acquired...\n",THREAD_ID);
P_V();
}
return 0;
}
/*
* unlock - Implements semaphore unlock functionality. System only
* provides a single semaphore for users.
*
* @args - Ignored
*
*/
int
unlock(int args)
{
if(DebugMutex)
{
P_P();
printf("Thread %d is releasing...\n",THREAD_ID);
P_V();
}
GlobalLock = 0;
if(DebugMutex)
{
P_P();
printf("Thread %d has released...\n",THREAD_ID);
P_V();
}
return 0;
}
/* thread - start up a pthread to evaluate an expression
* - car(args) := captured calling environment
* - cadr(args) := expression to be evaluated
*
* - the calling environment gets extended, and then the expression is evaluated
* under the extended environment
*/
int
thread(int args)
{
T_P();
++CreatedThreads;
++WorkingThreads;
P();
ENSURE_MEMORY(MAKE_ENVIRONMENT_SIZE+INTEGER_SIZE, &args , (int *) 0);
/* Extend the environment and create the pseudo-tid */
int env = makeEnvironment(car(args),0,0,0);
int expr = cadr(args);
int tid = ++ScamThreadID;
/* fatal if we exceed the thread limit */
if (tid > MAX_THREADS - 1)
{
V();
T_V();
Fatal("You have reached the max thread limit of %d\n", MAX_THREADS);
}
int ret = newIntegerUnsafe(tid);
ThreadQueue[tid].env = env;
ThreadQueue[tid].expr = expr;
ThreadQueue[tid].tid = tid;
V();
int *arg = malloc(sizeof(int));
*arg = tid;
int p_ret = pthread_create(&Thread[CreatedThreads-1], NULL, (void *)InternalThread,(void *)arg);
T_V();
if(p_ret)
{
Fatal("Error creating threads.\n");
}
return ret;
}
/*
* internalThread - This is the actual function called by thread when
* created a new pthread.
*/
static void *
InternalThread(void *data)
{
/* We save our thread id into the thread specific memory location */
pthread_setspecific(key,data);
printf("Tid: %d\n", *(int*)data);
/* Initialize memory for this thread */
memoryInit();
int tid = *(int *)data;
int result = eval(ThreadQueue[tid].expr,ThreadQueue[tid].env);
if (isThrow(result) || isError(result))
{
P_P();
if(StackDebugging)
{
printStack();
}
if(Debugging)
{
T_P();
printf("Error in thread %d (%d)\n" ,tid,WorkingThreads);
T_V();
ShuttingDown = 1;
QueueCount = 0;
debug("EXCEPTION",error_code(result));
scamPPFile(stdout,error_value(result));
printf("\n");
}
else
{
if(ThreadError == -1)
{
ThreadError = tid;
}
}
P_V();
}
T_P();
--WorkingThreads;
T_V();
memoryShutdown();
free(data);
Thread[tid] = (pthread_t)NULL;
pthread_exit(NULL);
return NULL;
}
/*
* tjoin - Interface for users to call join on their threads in SCAM
*
* @args - The thread ID to join on
*/
int
tjoin (int args)
{
int tid = ival(car(args));
// Might garbage collect and then wait with pthread_join
T_P();
--WorkingThreads;
T_V();
pthread_join(Thread[tid], NULL);
// I can now garbage collect again
T_P();
++WorkingThreads;
T_V();
return newInteger(tid);
}
/*
* getTID - Interface for users to get the current threads ID in SCAM
*/
int
getTID(int args)
{
int result;
P();
ENSURE_MEMORY(1,(int *) 0);
result = newIntegerUnsafe(THREAD_ID);
V();
return result;
}
/*
* checkDeadlock - Check to see if there is a deadlock between internal mutexes.
* if there is a deadlock a fatal is thrown.
*
* @f - File where possible deadlock occured
* @l - Line where possible deadlock occured
*/
void
checkDeadlock(char* f, int l)
{
int T1 = 0;
while(T1 < CreatedThreads-1)
{
int T2 = 0;
while( T2 < CreatedThreads)
{
/* P and P_P */
if ( (P_REQ[T1] == ACQUIRED && P_REQ[T2] == REQUESTED) &&
(P_P_REQ[T1] == REQUESTED && P_P_REQ[T2] == ACQUIRED))
{
printf("Deadlock between threads %d and %d.",T1,T2);
printf("Thread %d : Has P and wants P_P, Thread %d has P_P and wants P\n",T2,T2);
Fatal("Internal Error : Please let your instructor know");
}
/* P and T_P */
if ( (P_REQ[T1] == ACQUIRED && P_REQ[T2] == REQUESTED) &&
(T_P_REQ[T1] == REQUESTED && T_P_REQ[T2] == ACQUIRED))
{
printf("Deadlock between threads %d and %d.",T1,T2);
printf("Thread %d : Has P and wants T_P, Thread %d has T_P and wants P\n",T2,T2);
Fatal("Internal Error : Please let your instructor know");
}
/* P_P and T_P */
if ( (P_P_REQ[T1] == ACQUIRED && P_P_REQ[T2] == REQUESTED) &&
(T_P_REQ[T2] == REQUESTED && T_P_REQ[T2] == ACQUIRED))
{
printf("Deadlock between threads %d and %d.",T1,T2);
printf("Thread %d : Has P_P and wants T_P, Thread %d has T_P and wants P_P\n",T2,T2);
Fatal("Internal Error : Please let your instructor know");
}
++T2;
}
++T1;
}
}
/*
* validate - Compares the types of the thread Stack with the shadow stack.
* Returns 0 if something is wrong, 1 otherwise.
*/
int
validate(char *str)
{
if(StackDebugging)
{
int tid = THREAD_ID;
int st_len = STACK_SPOT;
int sh_len = SHADOW_SPOT;
if(st_len!=sh_len)
{
printf("Validating at %s\n" , str );
printf("Stacks differ in length (%d,%d) on thread %d\n",st_len,sh_len,tid);
return 0;
}
int *S = STACK;
int i = 0;
while( i < st_len )
{
S_CELL C = SHADOW[i];
int addr = S[i];
char *shadow = C.type;
char *light = type(addr);
if(shadow != light)
{
printf("Stack for thread %d : \n",tid);
printf("\t\tType = %s\n", type(addr));
printf("\t\tFile = %d\n", file(addr));
printf("\t\tLine = %d\n", line(addr));
printf("\t\tCount = %d\n", count(addr));
printf("\t\tIval = %d\n", ival(addr));
printf("\t\tRval = %f\n", rval(addr));
printf("\t\tFval = %p\n", fval(addr));
printf("\t\tCdr = %d\n\n", cdr(addr));
printf("Stack for thread %d : \n",tid);
printf("\t\tAddress = %d\n", C.addr);
printf("\t\tType = %s\n", C.type);
printf("\t\tFile = %d\n", C.file);
printf("\t\tLine = %d\n", C.line);
printf("\t\tCount = %d\n", C.count);
printf("\t\tIval = %d\n", C.ival);
printf("\t\tRval = %f\n", C.rval);
printf("\t\tFval = %p\n", C.fval);
printf("\t\tCdr = %d\n\n", C.cdr);
printf("\t\tFile Changed : %s\n", C.fileChanged);
printf("\t\tLine Changed : %d\n\n", C.lineChanged);
return 0;
}
++i;
}
}
return 1;
}
/* Enable or disable mutex debugging */
int
debugMutex(int args)
{
DebugMutex = SameSymbol(car(args),TrueSymbol);
return 0;
}
/* If there is an error in a thread this will return the thread id */
int
getThreadError(int args)
{
return newInteger(ThreadError);
}