LINUX线程分离

linux 环境中可以通过pthread_detach( phtread_id) 函数对线程进行分离

1.可以在子线程中加入代码 pthread_detach(pthread_self())

2.或者在父线程调用pthread_detach(thread_id)
使用简单的


#include 
#include 
#include 
#include 
 #include 
void *thread_function(void *arg)
{
// pthread_detach(pthread_self());在子线程中使用
 char* cmd = (char*)arg;
 printf("cmd: %s \n",cmd);
 system(cmd);
while(1);
}

void cmd (char * cmd1,char *cmd2,char * cmd3)
{
        pthread_t thread1,thread2,thread3;  
        /*char * cmd1 = "ls";
        char * cmd2 = "ls";
        char * cmd3 = "ls";
        */
    pthread_create(&thread1, NULL, thread_function, (void *)cmd1);  //        
        pthread_create(&thread2, NULL, thread_function, (void *)cmd2);
        pthread_create(&thread3, NULL, thread_function, (void *)cmd3);


        pthread_detach(thread1);  // 2 在主线程中分离线程      
        pthread_detach(thread2);
        pthread_detach(thread3);


}


int main()
{
        cmd("ls","ls","ls");

        sleep(2);
        printf("hahao end end ");
}

你可能感兴趣的:(C语言)