线程的创建和终止

 

拥有线程程序的编译需要加 -pthread

gcc a.c -o a -pthread

 

/*
        #include <pthread.h>

        int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                            void *(*start_routine) (void *), void *arg);
            功能:创建一个子线程
            参数:
                thread:传出参数,线程创建成功后,线程id会写到该参数中
                attr:需要设置的线程属性,一般使用默认值,NULL
                start_routine:函数指针,这个函数是子线程需要处理的逻辑代码
                arg:给第三个参数传参,不需要传递参数,就传NULL
            返回值:
                成功:0
                失败:错误号,与之前的errno不一样
                    因此不能使用perror,使用strerror
                    
        void pthread_exit(void *retval);
            功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
            参数:
                retval:作为返回值,可以通过pthread_join()获取
                    不需要返回值,则添NULL

        pthread_t pthread_self(void);
            功能:获取线程id

        int pthread_equal(pthread_t t1, pthread_t t2);
            功能:判断两个线程id是否相等
*/

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void *callback(void* arg)
{
    printf("child thread\n");
    printf("%d\n", *(int *)arg);
    return NULL; // == pthread_exit(NULL);
}


int main()
{
    pthread_t thread;
    // int errno = pthread_create(&thread, NULL, callback, NULL);

    int num = 10;
    int errno = pthread_create(&thread, NULL, callback, (void *)&num);


    if(errno != 0)
    {
        printf("%s\n", strerror(errno));
        exit(-1);
    }
    for(int i = 0; i < 5; i++)
    {
        printf("%d\n", i);
    }

    sleep(1);

    pthread_exit(NULL);


    return 0;
}

 

posted @ 2023-05-02 11:24  WTSRUVF  阅读(12)  评论(0编辑  收藏  举报