Hi, I have made a test myself and would like to share the results:
Code:
// test.cpp
#include <pthread.h>
#include <stdio.h>
#include "my_lib.h"
int main()
{
pthread_t thread1, thread2;
printf("Creating thread 1\n");
pthread_create(&thread1, NULL, foo1, NULL);
printf("Creating thread 2\n");
pthread_create(&thread1, NULL, foo2, NULL);
printf("Waiting for key press\n");
getchar();
}
Code:
// my_lib.h
#include <stdio.h>
#include <unistd.h>
void* foo1(void*);
void* foo2(void*);
Code:
// my_lib.cpp
#include "my_lib.h"
static int flag = 0;
void* foo1(void*)
{
while (true) {
printf("foo1: Flag is %d\n", flag);
sleep(1);
}
return NULL;
}
void* foo2(void*)
{
while (true) {
printf("foo2: Flag is %d\n", flag);
sleep(1);
flag++;
}
return NULL;
}
Both threads printed the incremented flag, i.e., the statement flag++ of foo2 of the second thread affected foo1 of the first thread.
I will try to solve this problem, thanks.