Skip to content

Instantly share code, notes, and snippets.

@Highstaker
Created February 10, 2018 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Highstaker/c1cb38fa06813351fab29dabbc98a5e9 to your computer and use it in GitHub Desktop.
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)
#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