Skip to content

Instantly share code, notes, and snippets.

@stephenmathieson
Created March 4, 2014 19:55
Show Gist options
  • Save stephenmathieson/9354321 to your computer and use it in GitHub Desktop.
Save stephenmathieson/9354321 to your computer and use it in GitHub Desktop.
Simple threaded concept for clib-install(1)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
/**
* Work structure.
*/
typedef struct {
int id;
char *slug;
int rc;
} install_work_t;
/**
* Simple wrapper around `install_package`.
*/
static void *
install_package_worker(void *data) {
install_work_t *work = (install_work_t *) data;
// actually do the installation here:
// work->rc = install_package(work->slug);
work->rc = 0;
pthread_exit(work);
}
/**
* Entry point.
*/
int
main(void) {
pthread_t threads[2];
install_work_t workers[2];
// get packages from args
char *packages[2] = {
"stephenmathieson/case.c"
, "stephenmathieson/trim.c"
};
// spawn threads
for (int i = 0; i < 2; i++) {
workers[i].id = i;
workers[i].slug = packages[i];
int rc = pthread_create(&threads[i]
, NULL
, install_package_worker
, (void *) &workers[i]);
if (0 != rc) {
fprintf(stderr, "Failed to create thread #%d (%s)\n", i, packages[i]);
exit(1);
}
}
// get thread status
for (int i = 0; i < 2; i++) {
void *status = NULL;
install_work_t *work = NULL;
pthread_join(threads[i], &status);
work = (install_work_t *) status;
if (0 == work->rc) {
printf("%s installed!\n", work->slug);
} else {
fprintf(stderr, "Failed to install %s\n", work->slug);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment