Skip to content

Instantly share code, notes, and snippets.

@johnmarinelli
Created September 6, 2016 23:42
Show Gist options
  • Select an option

  • Save johnmarinelli/a4d23c59bb532da2cf879531f5208e68 to your computer and use it in GitHub Desktop.

Select an option

Save johnmarinelli/a4d23c59bb532da2cf879531f5208e68 to your computer and use it in GitHub Desktop.
c threads
// gcc -g main.c -o a -lpthread
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef pthread_mutex_t mutex_t;
typedef struct {
int* ary;
mutex_t* mtx;
} thread_fn_args;
void insert_to_ary(int* ary, int val, int offset, mutex_t* mtx) {
pthread_mutex_lock(mtx);
*(ary + offset) = val;
pthread_mutex_unlock(mtx);
}
/* main() for a thread */
void* thread_fn(thread_fn_args* args) {
int i = 0;
int* ary = args->ary;
mutex_t* mtx = args->mtx;
while (i < 110) {
insert_to_ary(ary, i * -1, i, mtx);
++i;
}
}
int main(int argc, char* args[]) {
pthread_t t_hnd;
mutex_t mtx;
int i = 110;
int* ary = malloc(210 * sizeof(int));
printf("ary address: %p\n", (void*) ary);
thread_fn_args thread_args;
thread_args.ary = ary;
thread_args.mtx = &mtx;
pthread_create(&t_hnd, NULL, thread_fn, &thread_args);
pthread_mutex_init(&mtx, NULL);
while (i < 210) {
insert_to_ary(ary, i, i, &mtx);
++i;
}
printf("main waiting for thread to terminate\n");
pthread_join(t_hnd, NULL);
for (i = 0; i < 210; ++i) {
printf("%d ", *(ary + i));
}
free(ary);
ary = NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment