zoukankan      html  css  js  c++  java
  • Linux 多线程开发

    在任何一个时间点上,线程是可结合的(joinable)或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死。在被其他线程回收之前,它的存储器资源(例如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。

        默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该要么被显示地回收,即调用pthread_join;要么通过调用pthread_detach函数被分离。

    [cpp]
    int pthread_join(pthread_t tid, void**thread_return); 
                                     若成功则返回0,若出错则为非零。 

    int pthread_join(pthread_t tid, void**thread_return);
                                     若成功则返回0,若出错则为非零。    线程通过调用pthread_join函数等待其他线程终止。pthread_join函数分阻塞,直到线程tid终止,将线程例程返回的(void*)指针赋值为thread_return指向的位置,然后回收已终止线程占用的所有存储器资源。[cpp] view plaincopyprint?int pthread_detach(pthread_t tid); 
                                     若成功则返回0,若出错则为非零。 

    int pthread_detach(pthread_t tid);
                                     若成功则返回0,若出错则为非零。

        pthread_detach用于分离可结合线程tid。线程能够通过以pthread_self()为参数的pthread_detach调用来分离它们自己。
        如果一个可结合线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收,所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。

        由于调用pthread_join后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。例如,在Web服务器中当主线程为每个新来的连接请求创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的连接请求),这时可以在子线程中加入代码

        pthread_detach(pthread_self())

    或者父线程调用

        pthread_detach(thread_id)(非阻塞,可立即返回)

    这将该子线程的状态设置为分离的(detached),如此一来,该线程运行结束后会自动释放所有资源。

    C++创建线程函数

    #include <iostream>
    using namespace std;
    
    #include <pthread.h>
    
    
    void *Bar(void *arg)
    {
            cout << __PRETTY_FUNCTION__ << endl;
    }
    
    class Foo {
    public:
            Foo();
            ~Foo();
            static void * Bar(void *arg);
    private:
            pthread_t tid_self;
            pthread_t tid_other;
    };
    
    Foo::Foo()
    {
            pthread_create(&tid_self, NULL, &Bar, NULL);
            pthread_join(tid_self, NULL);
            pthread_create(&tid_other, NULL, &::Bar, NULL);
    }
    
    Foo::~Foo()
    {
            pthread_join(tid_other, NULL);
    }
    
    void * Foo::Bar(void *arg)
    {
            cout << __PRETTY_FUNCTION__ << endl;
    }
    
    int
    main(int argc, char *argv[])
    {
            Foo foo;
            return 0;
    }
    
  • 相关阅读:
    博客园设置自定义页面[布局][样式]
    linux的hostname文件目录
    mybatis底层源码分析之--配置文件读取和解析
    Enum的使用
    easyUI datagrid笔记
    软工实践第二次作业-黄紫仪
    软工实践第一次作业-黄紫仪
    第五次作业--原型设计
    作业三
    作业二
  • 原文地址:https://www.cnblogs.com/cslunatic/p/3478446.html
Copyright © 2011-2022 走看看