struct node
{
public:
char *s;
int up;
node()
{
up = 0;
s = new char[1000];
memset (s, 0, sizeof(char) * 1000);
}
~node()
{
delete [] s;
}
void insert()
{
s[up++] = 'a';
}
};
void* test_thread(void *arg)
{
pthread_mutex_lock( &mutex1 );
node n;
n.insert();
printf ("%s\n", n.s);
printf ("%x\n", &n);
pthread_mutex_unlock( &mutex1 );
pthread_exit(0);
//return 0;
}
supose this function will be executed by
pthread_create(&id1, NULL, test_thread, NULL);
pthread_create(&id2, NULL, test_thread, NULL);
and it is compiled by
g++ test_thread.cpp -o main -lpthread -g
its result is
a
40a001a0
a
40a001a0
In my Linux operator ,the address of node n in the two thread are the same!
I want to know why the address of node n in which the tho thread contains are the same?
Any answer is appreciated~~~
Thanks~~~
Add
sleep(1)before you exit the thread. Now you should see two different addresses but the same output of'a'. (you would needpthread_jointhough).Now if you want to print
'aa'then you might have to define node in global space or define it in main.With your current code the
lock/unlockdoes not have any use but once you use the shared memory the 2nd thread can not write until the 1st thread has finished.