Skip to content

Instantly share code, notes, and snippets.

@tcarmelveilleux
Created May 8, 2018 14:26
Show Gist options
  • Save tcarmelveilleux/967728df33215d66e2e126637270901c to your computer and use it in GitHub Desktop.
Save tcarmelveilleux/967728df33215d66e2e126637270901c to your computer and use it in GitHub Desktop.
Stack overflow pthread arguments passing example
/*
============================================================================
Name : thread_test.c
Author : Tennessee Carmel-Veilleux
Version :
Copyright : Public domain
Description : Simple args-passing example with pthreads
============================================================================
*/
// FIXME: THIS IS FOR A STACK OVERFLOW ANSWER: NOT ALL ERRORS CHECKED FOR MORE SUCCINT CODE
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
// You can have all you want in here to fully configure your thread. Try
// to have everything be immutable (not rely in things that change under
// your feet in other threads).
typedef struct {
unsigned long long large_serial_number;
const char *my_name;
pthread_t caller_thread;
} fun_thread_args_t;
#define NUM_LOOPS 5u
static void* _fun_thread_run(void *arg) {
// Get our thread args from the dynamically allocated thread args passed-in
fun_thread_args_t *thread_args = (fun_thread_args_t *)arg;
unsigned int counter = 0;
bool done = false;
while (!done) {
// Use args here in your thread loop
counter++;
printf("My name is: '%s', my number is: %llX, loop count: %u\n",
thread_args->my_name,
thread_args->large_serial_number,
counter);
if (counter >= NUM_LOOPS) {
printf("'%s' is sooooo done.\n", thread_args->my_name);
done = true;
} else {
sleep(1u);
}
}
// Free incoming args pointer before exiting the thread loop.
free(arg);
return NULL;
}
static pthread_t *_launch_fun_thread(pthread_t *thread, unsigned long long serial_number, const char *name) {
// TODO: Of course, error-handle all the return values properly ;)
// Allocate and prepare args for the thread
fun_thread_args_t *args = calloc(1, sizeof(args));
args->caller_thread = pthread_self();
args->large_serial_number = serial_number;
args->my_name = name;
int rc = pthread_create(thread, NULL, &_fun_thread_run, args);
if (0 == rc) {
return thread;
} else {
free(args);
return NULL;
}
}
int main(void) {
puts("The fun we are having!");
pthread_t fun_thread1;
pthread_t fun_thread2;
_launch_fun_thread(&fun_thread1, 0xABCDEF12345678ULL, "super FUN thread 1");
usleep(500UL * 1000UL);
_launch_fun_thread(&fun_thread2, 0xDEADBEEF55AA55ULL, "super FUN thread 2");
pthread_join(fun_thread1, NULL);
pthread_join(fun_thread2, NULL);
puts("We are done having fun :(");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment