Created
February 10, 2018 13:10
-
-
Save Highstaker/c1cb38fa06813351fab29dabbc98a5e9 to your computer and use it in GitHub Desktop.
An example of threading in C. Shows how one can pass results (via return or pointer argument)
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
void* t_routine(void* args){ | |
unsigned int i = 0; | |
int a; | |
printf("Running thread!\n"); | |
for(i=0;i<4000000000;i++){ | |
a = 2*2; | |
if(i%1000000000==0){ | |
printf("%u\n", i); | |
} | |
} | |
printf("Thread finished!\n"); | |
*((int*)args) = 42; | |
int* ret = malloc(sizeof(int)); | |
*ret = 100; | |
return ret; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
/* code */ | |
const int N_THREADS = 8; | |
pthread_t threads[N_THREADS]; | |
int* result = malloc(sizeof(int)); | |
void* status; | |
int i = 0; | |
printf("Launching!\n"); | |
for(i=0;i<N_THREADS;i++){ | |
pthread_create(&threads[i], NULL, t_routine, result); | |
} | |
for(i=0;i<N_THREADS;i++){ | |
pthread_join(threads[i], &status); | |
printf("%p\n", status); | |
printf("%d\n", *(int*)status); | |
free(status); | |
} | |
printf("Done!\n"); | |
// printf("%p\n", result); | |
printf("%d\n", *result); | |
free(result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment