
线程是程序中运行的任何程序的基础,是通过分配给操作系统的代码来创建,管理和控制程序本质上是不同的部分。在使用线程时,应特别注意如何正确关闭线程。只有正确关闭线程,才能保证系统能正确运行。
要正确关闭Linux下的线程,建议使用pthread_join()函数或pthread_detach()函数。
首先介绍pthread_join()函数,它是一个阻塞性函数,等待线程结束,当每个线程在创建的时候,都会返回一个引用线程的句柄;可以拿着这个句柄来调用pthread_join(),来等待指定的线程结束。下面是一个示例代码:
“`c
#include
…
pthread_t a_thread;
int ret =pthread_create(&a_thread, NULL, thread_function, parameter);
…
ret = pthread_join(a_thread, NULL);
if( ret!= 0)
{
fprintf(stderr, “pthread_join error: %s\n”, strerror(ret));
}
此外,pthread_detach()函数也可以很好的用来关闭线程。它将线程脱离主线程,不过他也有对应的句柄,当线程脱离之后,它会自动回收资源,不需要进程主动的回收资源:
```c
#include
...
pthread_t a_thread;
int ret =pthread_create(&a_thread, NULL, thread_function, parameter);
...
ret = pthread_detach(a_thread);
if (ret != 0)
{
fprintf(stderr, "pthread_detach error: %s\n", strerror(ret));
}
总结来说,Linux下有两种正确的线程关闭方法,一种是pthread_join()函数,它是一个阻塞函数,需要等待指定的线程结束;另一个是pthread_detach()函数,它将线程脱离主线程,让操作系统自动回收资源,无需进程主动的去控制回收资源。开发者可选择使用哪一种的依据自身的需求来决定。
香港服务器首选树叶云,2H2G首月10元开通。
树叶云(www.IDC.Net)提供简单好用,价格厚道的香港/美国云服务器和独立服务器。IDC+ISP+ICP资质。ARIN和APNIC会员。成熟技术团队15年行业经验。
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/163556.html<