Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

392 Threads Chapter 11


err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0)
err_exit(err, "can’t create thread 2");
sleep(1);
printfoo("parent:\n", fp);
exit(0);
}

Figure 11.4 Incorrect use ofpthread_exitargument

When we run this program on Linux, we get
$./a.out
thread 1:
structure at 0x7f2c83682ed0
foo.a = 1
foo.b = 2
foo.c = 3
foo.d = 4
parent starting second thread
thread 2: ID is 139829159933696
parent:
structure at 0x7f2c83682ed0
foo.a = -2090321472
foo.b = 32556
foo.c = 1
foo.d = 0
Of course, the results vary,depending on the memory architecture, the compiler,and
the implementation of the threads library.The results on Solaris aresimilar:
$./a.out
thread 1:
structure at 0xffffffff7f0fbf30
foo.a = 1
foo.b = 2
foo.c = 3
foo.d = 4
parent starting second thread
thread 2: ID is 3
parent:
structure at 0xffffffff7f0fbf30
foo.a = -1
foo.b = 2136969048
foo.c = -1
foo.d = 2138049024
As we can see, the contents of the structure(allocated on the stack of threadtid1)have
changed by the time the main thread can access the structure. Note how the stack of the
second thread (tid2)has overwritten the first thread’s stack.To solve this problem, we
can either use a global structure or allocate the structureusingmalloc.
Free download pdf