Add ability to spawn adder threads
parent
2c83d753d9
commit
0b21e8be9a
43
main.c
43
main.c
|
@ -1,8 +1,11 @@
|
|||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "adder.h"
|
||||
#include "mailbox.h"
|
||||
#include "main.h"
|
||||
|
||||
|
@ -71,6 +74,31 @@ static int get_input(int num_threads, struct input **res) {
|
|||
return input_index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the adder threads
|
||||
*
|
||||
* @param thread_ids An array of all of the thread ids to spawn, in order.
|
||||
* @param num_threads The number of threads to spawn
|
||||
* @param threads A pre-allocated array to hold the spawned threads.
|
||||
*
|
||||
* @return int -1 on error, 0 otherwise.
|
||||
*/
|
||||
static int start_adder_threads(int *thread_ids, int num_threads, pthread_t *threads) {
|
||||
for (int i = 0; i < num_threads; i++) {
|
||||
int create_result = pthread_create(&threads[i], NULL, adder, &thread_ids[i]);
|
||||
if (create_result != 0) {
|
||||
// Clean up all of the threads that have started if we have an error.
|
||||
for (int j = 0; j < i; j++) {
|
||||
pthread_kill(threads[i], SIGKILL);
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
struct input *inputs = NULL;
|
||||
if (argc < 2 || argc > 3) {
|
||||
|
@ -100,5 +128,20 @@ int main(int argc, char *argv[]) {
|
|||
return 1;
|
||||
}
|
||||
|
||||
// Must allocate an array of the ids to prevent a race condition when adder starts
|
||||
// We don't want the thread id to be deallocated.
|
||||
// We don't want to allocate an id for thread id 0, so we store all of the others.
|
||||
int mailbox_ids[num_threads];
|
||||
for (int i = 0; i < num_threads; i++) {
|
||||
mailbox_ids[i] = i + 1;
|
||||
}
|
||||
pthread_t threads[num_threads];
|
||||
int start_result = start_adder_threads(mailbox_ids, num_threads, threads);
|
||||
if (start_result != 0) {
|
||||
printf("Failed to start adder threads. (%s)\n", strerror(errno));
|
||||
free_mailboxes();
|
||||
return 1;
|
||||
}
|
||||
|
||||
free_mailboxes();
|
||||
}
|
Loading…
Reference in New Issue