Skip to content

Instantly share code, notes, and snippets.

@Taymindis
Created September 15, 2017 01:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Taymindis/3938e917aaae4fc480386f494be62f0e to your computer and use it in GitHub Desktop.
Save Taymindis/3938e917aaae4fc480386f494be62f0e to your computer and use it in GitHub Desktop.
MultiThreading read and write for Hazard Pointer Logic in C
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#define THREAD_RUN 100
typedef struct $
{
char s[50];
} concurrent_update;
static concurrent_update *a;
static concurrent_update *cus;
void * write(void* thr_data) {
int n;
concurrent_update *cu = cus + (*(int*)thr_data);
// RETRY:
for (n = 0; n < 1000; ++n) {
sprintf(cu->s, "thread id %ld\n", pthread_self() );
a = cu;
}
// goto RETRY;
// free(cu);
return 0;
}
void * read(void* thr_data)
{
int n;
// RETRY:
for (n = 0; n < 1000; ++n) {
printf("%s\n ", a->s);
}
// goto RETRY;
return 0;
}
int main(void)
{
int n;
pthread_t read_thr[THREAD_RUN];
pthread_t write_thr[THREAD_RUN];
concurrent_update *start = malloc(sizeof(concurrent_update));
cus = malloc(THREAD_RUN * sizeof(concurrent_update));
strcpy(start->s, "abcdeti");
a = start;
for (n = 0; n < THREAD_RUN; ++n) {
pthread_create(&write_thr[n], NULL, write, &n);
pthread_create(&read_thr[n], NULL, read, &n);
}
for (n = 0; n < THREAD_RUN; ++n)
pthread_join(read_thr[n], NULL);
for (n = 0; n < THREAD_RUN; ++n)
pthread_join(write_thr[n], NULL);
free(start);
free(cus);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment