我是C 编程的初学者我创建了一个新线程并且它工作正常,我的线程在接受时阻塞了代码。从外部调用pthread_cancel 是否会终止线程。或者我是否需要从外部关闭套接字。
在线程代码中,它是一个阻塞代码
while( (clientfd = accept(socketfd, (struct sockaddr *)&client,&clilen)) )
{
printf("New Client connected");
......
}
Run Code Online (Sandbox Code Playgroud)
从外部调用pthread_cancel
pthread_cancel(thread_id);
Run Code Online (Sandbox Code Playgroud)
发生什么了?
关于socket资源,你必须手动清理它,因为线程取消不会关闭你的资源。
您可以使用 cleanup_handler 来执行此操作,您应该查看pthread_cleanup_push() 和 void pthread_cleanup_pop。
一个简短的例子可以是:
void cleanup_handler(void *arg )
{
printf("cleanup \n");
// close your socket
}
void *execute_on_thread(void *arg)
{
pthread_cleanup_push(cleanup_handler, NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
while(1)
{
sleep(1);
printf("Running\n");
//thread stuff
}
pthread_cleanup_pop(1);
return (void *) 0;
}
int main( )
{
pthread_t tid;
pthread_create(&tid,NULL,execute_on_thread,NULL);
sleep(2);
if (!pthread_cancel(tid))
{
pthread_join(tid, NULL);
}
else
{
perror("pthread_cancel");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)