Created
September 13, 2021 05:00
-
-
Save wmoralesdev/e1b9eb2884823ad732c2b68a433471ea to your computer and use it in GitHub Desktop.
Thread example in C
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
// To compile in linux with gcc | |
// compile: gcc -pthread <filename>.c -o <filename> | |
// run: ./<filename> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <string.h> | |
// Struct for args aggrupation | |
typedef struct thread_data { | |
int a; | |
int b; | |
} thread_data; | |
void* writeToFileWithThread(void* x); | |
int main(void) { | |
// Declarate thread with id | |
pthread_t t; | |
// Setting args and capture value | |
thread_data arg; | |
arg.a = 15; | |
arg.b = 18; | |
void* captureVal = NULL; | |
// Create thread | |
// Args: thread id, attributes, start function, arguments passed to start | |
pthread_create(&t, NULL, writeToFileWithThread, &arg); | |
// Waits for thread terminantion | |
// Args: thread id, reference to capture value returned by thread | |
pthread_join(t, &captureVal); | |
printf("Returned message by thread: %s\n", (char*)captureVal); | |
return 0; | |
} | |
void* writeToFileWithThread(void* x) { | |
// Casting void ptr to known mem size | |
thread_data* nums = (thread_data *) x; | |
// File opening | |
FILE *f = fopen("file.txt", "w"); | |
// Handling not found file (must exist in current dir) | |
if(f == NULL) { | |
printf("Error opening file"); | |
exit(1); | |
} | |
// Writing to file and closing | |
fprintf(f, "Sum: %d\n", nums->a + nums->b); | |
fprintf(f, "Sub: %d\n", nums->a - nums->b); | |
fprintf(f, "Mul: %d\n", nums->a * nums->b); | |
fclose(f); | |
// Returning value to parent thread | |
return (void*) "success"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment