-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.c
More file actions
563 lines (474 loc) · 15.8 KB
/
threads.c
File metadata and controls
563 lines (474 loc) · 15.8 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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#include "ec440threads.h"
#include <stdlib.h>
#include <stdbool.h>
#include <setjmp.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
/* You can support more threads. At least support this many. */
#define MAX_THREADS 128
/* Your stack should be this many bytes in size */
#define THREAD_STACK_SIZE 32767
/* Number of microseconds between scheduling events */
#define SCHEDULER_INTERVAL_USECS (50 * 1000)
/* Extracted from private libc headers. These are not part of the public
* interface for jmp_buf.
*/
#define JB_RBX 0
#define JB_RBP 1
#define JB_R12 2
#define JB_R13 3
#define JB_R14 4
#define JB_R15 5
#define JB_RSP 6
#define JB_PC 7
/* thread_status identifies the current state of a thread. You can add, rename,
* or delete these values. This is only a suggestion. */
enum thread_status
{
TS_EXITED,
TS_RUNNING,
TS_READY,
TS_BLOCKED
};
/* The thread control block stores information about a thread. You will
* need one of this per thread.
*/
struct thread_control_block {
int tid; //Thread id (will be 0 to 127)
void * stackPtr; //Information about the stack
enum thread_status status; //Value about thread status (0 for reading, 1 for running)
jmp_buf currentContext; //Store jump buffer with current context information
struct thread_control_block * nextThread;
};
// Global thread variables: TCB table with ALL current threads and the currently running thread
struct TCBTable {
int size;
struct thread_control_block * currentThread;
struct thread_control_block * lastThread;
};
struct TCBTable * TCB;
void * stackToFree = NULL;
bool available[MAX_THREADS];
// Mutex Library data structure definitions:
enum lock_status {
MS_LOCKED,
MS_FREE,
MS_DESTROYED
};
// Mutex data structure that contains status and the head of the linked list of blocked threads
// Head points to first blocked thread so mutex_unlock can awaken them in order
typedef union my_pthread_mutex_t {
struct my_mutex_data {
enum lock_status status;
struct thread_control_block * head;
struct thread_control_block * tail;
}data;
pthread_mutex_t sys_mutex;
}my_pthread_mutex_t;
typedef union my_pthread_barrier_t {
struct my_barrier_data {
unsigned int count;
unsigned int num_blocked;
unsigned int valid;
struct thread_control_block ** threads;
}data;
pthread_barrier_t sys_barrier;
}my_pthread_barrier_t;
/*** Code Section ***/
// Helper function that locks the signals
static void lock(){
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig, SIGALRM);
sigprocmask(SIG_BLOCK, &sig, NULL);
}
// Helper function that unlocks signals
static void unlock(){
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig, SIGALRM);
sigprocmask(SIG_UNBLOCK, &sig, NULL);
}
static int schedule_initialized = 0;
// SIGALRM handler that saves current context and moves onto the next function
static void schedule(int sig)
{
// If a previous thread has exited, free the stack and set global stackToFree to NULL
if (stackToFree != NULL){
free(stackToFree);
stackToFree = NULL;
}
(void) ptr_demangle;
// Use setjmp to update currently active thread's jmp_buf, if jumped to = no scheduling
if(sigsetjmp(TCB->currentThread->currentContext, 1) == 0){
// If current thread is done, then free the thread and move on
if(TCB->currentThread->status == TS_EXITED){
struct thread_control_block * current = TCB->currentThread;
stackToFree = TCB->currentThread->stackPtr;
TCB->size--;
available[TCB->currentThread->tid] = true;
// If there are more threads, set up the next thread. Otherwise, do nothing.
if (current->nextThread != NULL){
TCB->currentThread = current->nextThread;
TCB->currentThread->status = TS_RUNNING;
if (TCB->currentThread->tid == 0 && TCB->size == 1){
free(stackToFree);
stackToFree = NULL;
}
free(current);
current = NULL;
// Initialize timer: Send SIGALRM in 50ms
if (ualarm(SCHEDULER_INTERVAL_USECS, 0) < 0){
printf("ERROR: Timer not set\n");
exit(-1);
}
// Go to the next thread to be run
siglongjmp(TCB->currentThread->currentContext, 1);
}
// Free the finished thread (don't need to free stack or context since those are freed in thread exit)
free(current);
current = NULL;
}
else if (TCB->currentThread->status == TS_BLOCKED){
// Initialize timer: Send SIGALRM in 50ms
if (ualarm(SCHEDULER_INTERVAL_USECS, 0) < 0){
printf("ERROR: Timer not set\n");
exit(-1);
}
// If the current thread is blocked, then take it out of the linked list
if (TCB->currentThread->nextThread != NULL){
struct thread_control_block * temp = TCB->currentThread;
TCB->currentThread = TCB->currentThread->nextThread;
TCB->currentThread->status = TS_RUNNING;
temp->nextThread = NULL;
siglongjmp(TCB->currentThread->currentContext, 1);
}
// If rest is empty, just set everything to NULL (shouldn't reach here)
else{
printf("Whoops! You shouldn't be here\n");
TCB->currentThread = NULL;
TCB->lastThread = NULL;
}
}
else{
// Initialize timer: Send SIGALRM in 50ms
if (ualarm(SCHEDULER_INTERVAL_USECS, 0) < 0){
printf("ERROR: Timer not set\n");
exit(-1);
}
TCB->currentThread->status = TS_READY;
// If a next thread exists, set all the pointers and jump to new thread
if (TCB->currentThread->nextThread != NULL){
// Move from current thread to next thread and move current to last thread
TCB->lastThread->nextThread = TCB->currentThread;
TCB->lastThread = TCB->currentThread;
TCB->currentThread = TCB->currentThread->nextThread;
TCB->lastThread->nextThread = NULL;
TCB->currentThread->status = TS_RUNNING;
// Jump to the next thread
siglongjmp(TCB->currentThread->currentContext, 1);
}
// If there is no more next threads but the current thread is not done, just keep running
}
}
}
// Scheduler_init function for initializing global variables and main thread
static void scheduler_init()
{
// Allocate memory for the TCB table with MAX_THREADS entries
TCB = (struct TCBTable *) malloc(sizeof(struct TCBTable) + 2 * sizeof(struct thread_control_block));
TCB->size = 0;
TCB->currentThread = (struct thread_control_block *) malloc(sizeof(struct thread_control_block));
TCB->currentThread->nextThread = NULL;
TCB->currentThread->stackPtr = NULL;
TCB->currentThread->status = TS_RUNNING;
TCB->currentThread->tid = TCB->size++;
TCB->lastThread = TCB->currentThread;
// Initialize array of which tid's are available
for(int i = 0; i < MAX_THREADS; i++)
available[i] = true;
available[0] = false;
// Set signal handler to schedule
struct sigaction sigAlrmAction;
memset(&sigAlrmAction, 0, sizeof(sigAlrmAction));
sigemptyset(&sigAlrmAction.sa_mask);
sigAlrmAction.sa_flags = 0;
sigAlrmAction.sa_handler = schedule;
sigaction(SIGALRM, &sigAlrmAction, NULL);
// Initialize timer: Every 50ms sends SIGALRM
if (ualarm(SCHEDULER_INTERVAL_USECS, 0) < 0){
printf("ERROR: Timer not set\n");
exit(-1);
}
}
// Thread creation function that allocates and initializes values for a new thread.
int pthread_create(
pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg)
{
// Create the timer and handler for the scheduler. Create thread 0.
if (schedule_initialized == 0)
{
schedule_initialized = 1;
scheduler_init();
// Save context of main thread (current only thread), leave if longjmp'd here
if(sigsetjmp(TCB->currentThread->currentContext, 1) != 0)
return 0;
}
if (TCB->size >= MAX_THREADS){
*thread = (pthread_t) -1;
printf("ERROR: Max number of threads reached\n");
return -1;
}
struct thread_control_block * newThread = (struct thread_control_block *) malloc(sizeof(struct thread_control_block));
newThread->nextThread = NULL;
newThread->status = TS_READY;
// Iterate through all tid's and find first available one. If none are available, print error and return
int i = 0;
bool found = false;
while(i < MAX_THREADS && !found){
if(available[i]){
newThread->tid = i;
available[i] = false;
found = true;
break;
}
i++;
}
if(!found){
free(newThread);
*thread = (pthread_t) -1;
printf("ERROR: No available threads\n");
return -1;
}
// Create the stack: Dynamically allocate memory
void * stackPtr = malloc(THREAD_STACK_SIZE);
*(unsigned long *) (stackPtr + THREAD_STACK_SIZE - 8) = (unsigned long) &pthread_exit;
newThread->stackPtr = stackPtr;
//ptr mangle start_thunk and the pthread_exit thing
sigsetjmp(newThread->currentContext, 1);
newThread->currentContext[0].__jmpbuf[JB_RSP] = ptr_mangle( (unsigned long) stackPtr + THREAD_STACK_SIZE - 8);
newThread->currentContext[0].__jmpbuf[JB_R12] = (unsigned long) start_routine;
newThread->currentContext[0].__jmpbuf[JB_R13] = (unsigned long) arg;
newThread->currentContext[0].__jmpbuf[JB_PC] = ptr_mangle( (unsigned long) start_thunk );
*thread = (pthread_t) newThread->tid;
TCB->lastThread->nextThread = newThread;
TCB->lastThread = newThread;
TCB->lastThread->nextThread = NULL;
TCB->size++;
return 0;
}
// Exit function that runs whenever a thread has exited either implicitly or explicitly
void pthread_exit(void *value_ptr)
{
// Cancel any current alarms
ualarm(0,0);
// Set the current thread's status to exited
TCB->currentThread->status = TS_EXITED;
// Run schedule to free values and set the next thread to be run
schedule(0);
// No more threads to jump to => free the linked list and exit
free(TCB);
exit(0);
}
// Function that returns the thread id of the currently running thread
pthread_t pthread_self(void)
{
if (TCB->size > 0){
// Return tid of current thread
return (pthread_t) TCB->currentThread->tid;
}
return (pthread_t) -1;
}
// Mutex function that initializes the mutex values
int pthread_mutex_init(pthread_mutex_t * restrict mutex,
const pthread_mutexattr_t * restrict attr){
if (!schedule_initialized){
scheduler_init();
schedule_initialized = 1;
}
// Initialize data structure for mutex (set to free and empty LL)
my_pthread_mutex_t * my_mutex = (my_pthread_mutex_t *) mutex;
my_mutex->data.status = MS_FREE;
my_mutex->data.head = NULL;
my_mutex->data.tail = NULL;
return 0;
}
// Mutex function used to destroy the inputted mutex
int pthread_mutex_destroy(pthread_mutex_t * mutex){
// Lock UALARM signals
lock();
my_pthread_mutex_t * my_mutex = (my_pthread_mutex_t *) mutex;
my_mutex->data.status = MS_DESTROYED;
// Unlock UALARM signals
unlock();
return 0;
}
// Mutex function used to lock current thread or block until resource available
int pthread_mutex_lock(pthread_mutex_t * mutex){
// Lock UALARM signals
lock();
my_pthread_mutex_t * my_mutex = (my_pthread_mutex_t *) mutex;
// If mutex doesn't exist, then return error
if (my_mutex == NULL || my_mutex->data.status == MS_DESTROYED || TCB->currentThread == NULL){
// Unlock UALARM signals
unlock();
return -1;
}
// Initialize thread node to be added to the linked list
struct thread_control_block * cur_thread = TCB->currentThread;
// Check if thread still exists
if (cur_thread == NULL){
return -1;
}
// If mutex is free, simply lock it and give it to the current thread (continue on with its day)
if (my_mutex->data.status == MS_FREE){
my_mutex->data.status = MS_LOCKED;
}
// If mutex is being used, initialize queue if needed and add it to the queue
else{
// If empty, set the next values to be used
// If queue is empty, initialize to the current values (Queue ONLY has threads WAITING FOR LOCK)
if (my_mutex->data.head == NULL){
my_mutex->data.head = cur_thread;
my_mutex->data.tail = cur_thread;
}
// If queue is not empty, just append to the end
else{
my_mutex->data.tail->nextThread = cur_thread;
my_mutex->data.tail = cur_thread;
}
cur_thread->status = TS_BLOCKED;
unlock();
schedule(SIGALRM);
}
// Unlock UALARM signals
unlock();
return 0;
}
// Mutex unlock function used to unlock a resource and notify first blocked
int pthread_mutex_unlock(pthread_mutex_t *mutex){
// Lock UALARM signals
lock();
my_pthread_mutex_t * my_mutex = (my_pthread_mutex_t *) mutex;
// If mutex doesn't exist or mutex is already free then return error
if (my_mutex == NULL || my_mutex->data.status == MS_DESTROYED || TCB->currentThread == NULL){
// Unlock UALARM signals
unlock();
return -1;
}
// If mutex is already free, do nothing
if (my_mutex->data.status == MS_FREE || my_mutex->data.head == NULL){
// If there are no blocked threads and it's being unlocked, simply set the status to free
if (my_mutex->data.status == MS_LOCKED && my_mutex->data.head == NULL){
my_mutex->data.status = MS_FREE;
}
// Unlock UALARM signals
unlock();
return 0;
}
// Know that head is NOT null, so free next ready thread
struct thread_control_block * temp = my_mutex->data.head->nextThread;
my_mutex->data.head->status = TS_READY;
TCB->lastThread->nextThread = my_mutex->data.head;
TCB->lastThread = my_mutex->data.head;
TCB->lastThread->nextThread = NULL;
my_mutex->data.head = temp;
// If queue is now empty, reset pointers
if (temp == NULL){
my_mutex->data.head = NULL;
my_mutex->data.tail = NULL;
}
// Unlock UALARM signals
unlock();
return 0;
}
// Barrier initialization function that creates barrier
int pthread_barrier_init(pthread_barrier_t *restrict barrier,
const pthread_barrierattr_t *restrict attr,
unsigned count){
// Lock UALARM signals
lock();
// Check if count value is valid
if (count <= 0){
// printf("Error: Not a valid count value\n");
// Unlock UALARM signals
unlock();
return EINVAL;
}
my_pthread_barrier_t * my_barrier = (my_pthread_barrier_t *) barrier;
// Initialize the data structure and allocate memory for it
my_barrier->data.count = count;
my_barrier->data.num_blocked = 0;
my_barrier->data.valid = 1;
my_barrier->data.threads = (struct thread_control_block **) malloc(count * sizeof(struct thread_control_block *));
// Unlock UALARM signals
unlock();
return 0;
}
// Barrier function used to destroy current barrier
int pthread_barrier_destroy(pthread_barrier_t *barrier){
// Lock UALARM signals
lock();
my_pthread_barrier_t * my_barrier = (my_pthread_barrier_t *) barrier;
// Check if barrier exists
if (my_barrier == NULL){
// printf("Error: No barrier specified\n");
// Unlock UALARM signals
unlock();
return -1;
}
my_barrier->data.valid = 0;
// Lock UALARM signals
unlock();
return 0;
}
// Barrier function used to block current thread until barrier broken
int pthread_barrier_wait(pthread_barrier_t *barrier){
// Lock UALARM signals
lock();
my_pthread_barrier_t * my_barrier = (my_pthread_barrier_t *) barrier;
// Check if barrier exists
if (my_barrier == NULL || my_barrier->data.valid == 0){
// printf("Error: No barrier specified\n");
// Unlock UALARM signals
unlock();
return -1;
}
// Increment number of blocks currently in the barrier, if it's equal to count then awaken all threads
my_barrier->data.num_blocked++;
if (my_barrier->data.num_blocked >= my_barrier->data.count){
// Iterate through all threads in barrier and set all to ready and add them to the schedule
for (int i = 0; i < my_barrier->data.count-1; i++){
my_barrier->data.threads[i]->status = TS_READY;
TCB->lastThread->nextThread = my_barrier->data.threads[i];
TCB->lastThread = my_barrier->data.threads[i];
}
// Initialize timer: Send SIGALRM in 50ms
if (ualarm(SCHEDULER_INTERVAL_USECS, 0) < 0){
printf("ERROR: Timer not set\n");
// Unlock UALARM signals
unlock();
exit(-1);
}
my_barrier->data.num_blocked = 0;
// Unlock UALARM signals
unlock();
//return PTHREAD_BARRIER_SERIAL_THREAD;
return -1;
}
// If barrier is not full yet, add current thread to the barrier and schedule it to get taken out of schedule (return 0 when back)
else{
// Add thread to list and block it
my_barrier->data.threads[my_barrier->data.num_blocked-1] = TCB->currentThread;
TCB->currentThread->status = TS_BLOCKED;
schedule(SIGALRM);
// Unlock UALARM signals
unlock();
return 0;
}
}