kaitian521
kaitian521

Reputation: 578

local variables in threading function in Linux?

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~~~

Upvotes: 0

Views: 185

Answers (2)

D Untouchable
D Untouchable

Reputation: 352

Add sleep(1) before you exit the thread. Now you should see two different addresses but the same output of 'a'. (you would need pthread_join though).

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/unlock does not have any use but once you use the shared memory the 2nd thread can not write until the 1st thread has finished.

Upvotes: 0

Seg Fault
Seg Fault

Reputation: 1351

The object 'node n' is stack-local, so each of the two threads has their own 'node'. This explains why each time you see only one 'a' intead of two of them.

By the time the second thread starts, the first one has probably already finished, including freeing the memory, so that the second thread gets the same memory block again, that explains the same address.

If you want both threads to work on the same 'node' you need to make it a global variable, or allocate one and pass the pointer as fourth argument to pthread_create() so that it will be passed on to test_thread().

Upvotes: 2

Related Questions