Created
April 20, 2017 19:54
-
-
Save moiz-frost/b1e89fd1a3e3d459ef51ca7f474e23f0 to your computer and use it in GitHub Desktop.
Addition of numbers using threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Run 'gcc -pthread pthread.c -o exec' to compile | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#define LINE_READ_SIZE 100 | |
void *addAllNumbersFromList(void *listOfNumbers) | |
{ | |
int sumResult = 0; // stores the result of sum | |
char *token; // tokenized value | |
char *pointer = '\0'; // pointer for strtod | |
const char stringDelimiter[2] = " "; // delimiter | |
token = strtok(listOfNumbers, stringDelimiter); // initial tokenization | |
while(token != NULL) | |
{ | |
sumResult = sumResult + strtod(token, &pointer); | |
token = strtok(NULL, stringDelimiter); | |
} | |
if(sumResult != 0) | |
{ | |
printf("Sum is %d\n", sumResult); | |
} | |
pthread_exit(0); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
pthread_t thread; // thread ID | |
char *terminalLineBuffer[LINE_READ_SIZE]; // for reading from terminal | |
int terminalLineCount = read(STDIN_FILENO, &terminalLineBuffer, LINE_READ_SIZE); | |
if(terminalLineCount < 0) | |
{ | |
perror("Terminal Read Error"); | |
exit(0); | |
} | |
int threadReturnValue = pthread_create(&thread, NULL, addAllNumbersFromList, (void *) terminalLineBuffer); // create a thread task | |
// Do some other work while thread is executing | |
//sleep(2); | |
write(STDOUT_FILENO, "Doing some other work...\n", sizeof("Doing some other work...\n")); | |
// Finish doing some other work | |
if(threadReturnValue < 0) | |
{ | |
perror("Thread Error"); | |
} | |
pthread_join(thread, NULL); // waits until a thread is complete so that the program doesn't exit before thread execution | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment