I change a global variable in one thread, and the change will not take effect in another thread if I do not print it
Here's the code:
pthread_t thread_test[2];
bool test=true;
void* test1(void*)
{
while(1)
{
//printf("test: %d\n",test);
if(test)
continue;
printf("test test test\n");
usleep(500000);
}
}
void* test2(void*)
{
int i=0;
while(i<5)
{
printf("i: %d\n",i++);
sleep(1);
}
test=false;
return NULL;
}
int main()
{
pthread_create(&thread_test[0], NULL, &test1, (void *)NULL);
pthread_create(&thread_test[1], NULL, &test2, (void *)NULL);
pthread_join(thread_test[0],NULL);
return 0;
}
If the line printf("test: %d\n",test); is commented out.Then the change of test in test2 will not take effect in test1.
The run results are shown in below: enter image description here
if don't commented out it: enter image description here
This has troubled me for a long time. Wish someone please answer it.