I've been reference this link -> https://gist.github.com/Taymindis/3938e917aaae4fc480386f494be62f0e and do some valgrind check, it has no error. But I just want to double confirm is this example below consider thread safe?
I've personally vagrind check, it has no error, Does anyone has any better idea?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#define THREAD_RUN 100
static char *global;
static char *x1 = "This is thread 1";
static char *x2 = "This is thread 2";
void * write(void* thr_data) {
int n = *(int*)thr_data;
if(n%2==0) goto RETRY1;
else goto RETRY2;
RETRY1:
for (n = 0; n < 1000; ++n) {
global = x1;
}
goto RETRY1;
RETRY2:
for (n = 0; n < 1000; ++n) {
global = x2;
}
goto RETRY2;
// free(cu);
return 0;
}
void * read(void* thr_data)
{
int n;
RETRY:
for (n = 0; n < 1000; ++n) {
if(global[0] == 'C');
}
goto RETRY;
return 0;
}
int main(void)
{
int n;
pthread_t read_thr[THREAD_RUN];
pthread_t write_thr[THREAD_RUN];
global = x1;
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);
}