realdraickin 11 Newbie Poster

Hi, everyone and first off thank you for this great community!
So, here is my question about my code:

#include <pthread.h>
#include <stdio.h>

int data; // global variable

void *thread_function1(void *arg)
{
	int temp,i,j;

	printf("I'm threadf1\n");
	for (i=1;i<=20;i++)
	{
		data++;
		temp=data;
		temp+=3;
		j=0;
		while ( (j++)<1000000 );
		data=temp;
	}
	pthread_exit(NULL);
}


void *thread_function2(void *arg)
{
	int temp,i,j;
	printf("I'm threadf2\n");
	for (i=1;i<=20;i++)
	{
		data--;
		temp=data;
		temp-=3;
		j=0;
		while ( (j++)<1000000 );
		data=temp;
	}
	pthread_exit(NULL);
}

int main()
{
pthread_t mythread1[8],mythread2[8];
int i;
for (i=0;i<8;i++)
{
	pthread_create(&mythread1[i],NULL,thread_function1,NULL);
	pthread_create(&mythread2[i],NULL,thread_function2,NULL);
}

for (i=0;i<8;i++)
{
	pthread_join(mythread1[i],NULL);
	pthread_join(mythread2[i],NULL);
}

printf("Data is: %d\n",data);
pthread_exit(NULL);
}

The code above is supposed to output a 0 value for the global variable "data".
But it didn't (I guessed because it needed the use of mutex).To fix it I used
mutex on both functions and it finally worked.
But then, when I removed the temp variable from the functions and made it
global and then removed the while loops ( I did that to this code, the one without
the mutex) the problem got fixed again and the output for data was 0! How?
I hope I wasn't too confusing... Just a point to the right direction would be fine.
Thank you in advance for your time.

William Hemsworth commented: Great first post. +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.