线程创建

/***
pthread.c
***/
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>

void * func(void *arg)
{
    printf("func run...
");
    return NULL;
}

int main()
{
    pthread_t t1;
    int err = pthread_create(&t1,NULL,func,NULL);
    if( 0 != err)
    {
        printf("thread_create failled : %s
",strerror(errno));
    }
    else
    {
        printf("thread_create success
");
    }
    sleep(1);
    return EXIT_SUCCESS;
}

strerror() 包含在string.h的函数中

EXIT_SUCCESS 定义包含在stdlib.h的函数中

运行结果:

exbot@ubuntu:~/wangqinghe/thread/20190729$ ./thread

thread_create success

func run...

函数声明:

int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void *(*start_routine)(void*),void *arg);

在main函数里面调用上面的函数进行创建一个线程

函数参数:

第一个参数:pthread_t代表创建线程的唯一标识,是一个结构体,需要我们创建好后,将指针传递过去。

第二个参数:pthread_attr_t,代表创建这个线程的一些配置,比如分配的栈的大小,一般填NULL,表示使用默认的创建线程的配置。

第三个参数:代表一个函数的地址,创建线程时,会调用这个函数,函数的返回值是void*函数的参数也是void*,一般格式就像void *func(void *arg){}

第四个参数:代表调用第三个函数传递的参数

函数的返回值:

函数成功返回0,不等于0则代表函数调用失败,此时可以通过strerror(errno)可以打印出具体错误。

注意:每个线程都拥有一份errno副本,不同线程拥有不同的errno

编译时需要连接pthread.so库

exbot@ubuntu:~/wangqinghe/thread/20190729$ gcc thread.c -o thread –lpthread

使用sleep时为了防止新创建的线程还没运行到打印的方法主线程就结束了,而主线程结束,所以线程都会结束。

原文地址:https://www.cnblogs.com/wanghao-boke/p/11262416.html