问题描述
我在创建分离线程时遇到问题.这是我写的代码:
I have a problem creating a thread as detached. Here's the code I wrote:
void* testFunction() {
pthread_attr_t attr;
int chk,rc;
pthread_attr_init(&attr);
printf("thread_attr_init: %d\n",rc);
pthread_attr_getdetachstate(&attr, &chk);
printf("thread_attr_getdetachedstate: %d\n",rc);
if(chk == PTHREAD_CREATE_DETACHED )
printf("Detached\n");
else if (chk == PTHREAD_CREATE_JOINABLE)
printf("Joinable\n");
return NULL;
}
int main (int argc, const char * argv[]) {
pthread_t thread1;
pthread_attr_t attr;
int rc;
rc = pthread_attr_init(&attr);
printf("attr_init: %d\n",rc);
rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("attr_setdetachedstate: %d\n",rc);
rc = pthread_create(&thread1, &attr, testFunction, NULL);
printf("attr_create: %d\n",rc);
sleep(4);
pthread_cancel(thread1);
return 0;
}
问题是testFunction()
始终打印"Joinable".谁能告诉我我哪里出问题了?
The problem is that testFunction()
always print "Joinable". Can anyone tell me where I'm getting wrong?
推荐答案
您的testFunction
并未检查有关当前线程的任何内容,而只是检查您刚创建的全新属性对象的最初分离的标志.此外,在POSIX线程API中,完全不可能恢复创建线程所使用的属性或确定线程是否分离.您只需要相信实现可以按要求运行,就像您必须相信,如果malloc(100)
返回非空指针,它指向可以存储至少100个字节的位置.这就是C的本质.
Your testFunction
is not examining anything about the current thread, rather just the initially-detached flag of a completely new attribute object you just created. Moreover, it is completely impossible, in the POSIX threads API, to recover the attributes a thread was created with or determine if a thread is detached or not. You simply have to trust that the implementation behaves as required, just like you have to trust that, if malloc(100)
returns a non-null pointer, it points to a location at which you can store at least 100 bytes. This is the nature of C.
这篇关于Pthread创建为分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!