#include <iostream>

#include <thread>

#include <unistd.h>//slleep头文件

using namespace std;

void * mythread(void *)

 

{

        cout<<"子线程运行成功"<<endl;

        return 0;

//      sleep(10);

 

}

 

int main()

{

 

        pthread_attr_t attr;//设置状态分离的变量

        pthread_t thread;

        pthread_attr_init( &attr);//状态分离初始化

 

        //设置状态

        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

 

        //创建子进程时将状态设置为&attr

        int ret=pthread_create(&thread,&attr,mythread,NULL);

 

//      int ret=pthread_create(&thread,NULL,mythread,NULL);

 

        if(ret!=0)

        {

        cout<<"线程创建错误"<<endl;

        }

         pthread_attr_destroy(&attr);//状态变量需要销毁

        ret=pthread_join(thread,NULL);

 

        //检验是否状态分离成功

        if(ret!=0)

        {

        cout<<"线程状态已经分离"<<endl;

        }

        sleep(10);//在主线程运行结束之前等代子线程结束

        return 0;

 

}

 

posted on 2022-03-15 19:54  down^to^earth  阅读(20)  评论(0)    收藏  举报