is multithreading swapping 2 predefined pointer to one static variable causing memory error? | Sololearn: Learn to code for FREE!
- 2

is multithreading swapping 2 predefined pointer to one static variable causing memory error?

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); }

27th Sep 2017, 1:14 AM
minika woon
minika woon - avatar
4 Réponses
+ 2
Did you .... just answered your own question as if you was someone else ? :o
27th Sep 2017, 4:54 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
Well, Based on the coding logic regardless infinite loop, if you concern about memory corruption, I will said “no It won’t be happen due to assignment point is eventually assigned x1 or x2. I think you are not clear enough what is not guarantee assignment is atomic, if your program has multiple thread doing assignment to one global variable, it will not guarantee you that each of assignment is successfully assigned to it. Based on that, it might have a lot of x1 assignment has lost assigned or the other one. Back to what is your main purpose of this code, if your are planning to change pointer time to time and multiple read operation. I suggest you only 1 thread to do assignment
27th Sep 2017, 1:16 AM
minika woon
minika woon - avatar
0
Actually I’m posting for new suggestion, who knows refer back to the same link... so far the user oktaheta is quite correct to me. But I need more answer
27th Sep 2017, 4:57 AM
minika woon
minika woon - avatar
0
@Gordie I will take note next time. Meanwhile, I need you guys acknowledge whether the answer is correct or not based on my answer posted
27th Sep 2017, 6:30 AM
minika woon
minika woon - avatar