pthread_create pthread_join preate_detache

编译环境 Ubuntu18.04 G++


简单的demo demo里创建了两次线程 注释掉的代码是使用pthread_join的 现在用的是pthread_detach
总结一下

pthread_create 就是创建一个线程


第一个参数就是线程id号 先int id;
然后把id的引用传进去就可以保存id号了
第三个参数是要执行的函数 如果函数返回了 此线程也会返回
其他两个参数就不解释了

pthread_join和pthread_detach

首先线程分为两种,joinable和detached

pthread_join 会等待线程终止 类似waitpid

pthread_join()是一个阻塞调用,它将阻塞调用线程,直到另一个线程结束。

pthread_join()的第一个参数是目标线程的ID。
pthread_join()的第二个参数是(void *)的地址,即(void **),它将指向线程函数的返回值,即指向(void *)的指针。
pthread_detach

分离的线程在退出时自动释放其分配的资源。 没有其他线程需要加入它。 但是默认情况下,所有线程都是可连接的,因此要分离一个线程,我们需要使用线程ID调用pthread_detach(),即
另外,由于分离线程在退出时自动释放资源,因此无法确定分离线程功能的返回值。
如果发生错误,pthread_detach()将返回非零值。

#include <pthread.h>
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
using namespace std;

void * funct(void * arg)
{
    static int i=0;
    
  
    printf("hello %d
",i);
    i++;
    sleep(4);
    printf("wake UP%d
",i);
    i++;

    
}
int main()
{
    pthread_t  threadFunctID;

    int returnvalue=pthread_create(&threadFunctID,NULL,&funct,NULL);
    if (returnvalue)
    {
        //成功为0 失败有值
        printf("error");
    }
    else
    {
        
        printf("success
");
        cout<<"thread1 ID is "<<threadFunctID<<endl;
    }
      cout<<pthread_self<<"!!!!!"<<endl;
    int returnvalue2=pthread_create(&threadFunctID,NULL,&funct,NULL);
    if (returnvalue2)
    {
        //成功为0 失败有值
        printf("error");
    }
    else
    {
        
        printf("success
");
        cout<<"thread2  ID is"<<threadFunctID<<endl;
    }
      cout<<pthread_self<<"!!!!!"<<endl;
    //way2 use detach
    int err=pthread_detach(threadFunctID);
    if(err)
    {
        cout<<"error"<<endl;
    }
    sleep(8); //the main function wait for thread to exit 
    // you can test it for change the 
//way1 use join
    // cout<< "wait for thread to exit
";

    // returnvalue=pthread_join(threadFunctID,NULL);
    // if(returnvalue)
    // {
    //     printf("error");

    // }
    cout<<"Exit main
";
    return 0;
}
原文地址:https://www.cnblogs.com/yahoo17/p/12636521.html