- 论坛徽章:
- 0
|
在unix高级编程2中,关于pthread_detach有以下描述:
a thread's termination status is retained until pthread_join is called for that thread. A thread's underlying storage can be reclaimed immediately on termination if that thread has been detached. When a thread is detached, the pthread_join function can't be used to wait for its termination status. A call to pthread_join for a detached thread will fail, returning EINVAL. We can detach a thread by calling pthread_detach.
因此我想先对一个子线程调用pthread_detach,然后再对其pthread_join,测试一下是否会返回EINVAL值。但结果有点迷惑不解。
#include <pthread.h>
#include <iostream>
#include <errno.h>
using namespace std;
pthread_t ntid;
void
printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
(unsigned int)tid, (unsigned int)tid);
}
void *
thr_fn(void *arg)
{
printids("new thread: ");
int err = pthread_detach(pthread_self());
if (err != 0)
{
printf("can't detach thread: err = %d, %s\n", err, strerror(err));
}
return((void *)0);
}
int
main(void)
{
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0)
printf("can't create thread: %s\n", strerror(err));
printids("main thread:");
sleep(1); //这个sleep非常重要,是否存在会产生不同的结果
err = pthread_join(ntid, NULL);
if (err != 0)
{
printf("can't join thread: err = %d, %s\n", err, strerror(err));
}
return 0;
} |
当main函数中的sleep(1)语句存在时,回来的结果正确为:
main thread: pid 573810 tid 1 (0x1)
new thread: pid 573810 tid 258 (0x102)
can't join thread: err = 22, Invalid argument
但注释该sleep(1)时,程序的结果会是:
main thread: pid 573810 tid 1 (0x1)
new thread: pid 573810 tid 258 (0x102)
也就是说pthread_join正确处理了,返回了0.
我猜测是否是因为子线程在pthread_detach后,资料还未来得及释放,join函数就开始调用了,才导致该结果? |
|