driver用户态学习记录2----多线程(1)pthread_create, pthread_once, pthread_self和pthread_join

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>  //sleep()

#define NUM_THREADS 6

/*
函数原型:  int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_routine) (void*), void *arg);
参数:
pthread_t *tidp:如果创建成功,则*tidp为新创建线程的线程ID;
const pthread_attr_t *attr:用于指定线程的属性;
void *(*start_routine) (void*):为新创建线程的入口函数;
void *arg:线程入口函数start_routine的输入参数。
返回值:如果线程创建成功,则返回0;如果创建失败则返回出错编号。
功能:该函数用于创建线程。
使用注意事项:pthread是POSIX线程库,因此编译时需要加上-lpthread显示链接该库。
*/

/*
函数原型:pthread_t pthread_self(void);
功能:获得线程自身的ID。pthread_t类型是unsigned long int,需要用%lu打印
*/

/*
函数原型:  int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));
功能:该函数使用初始值为PTHREAD_ONCE_INIT的once_control变量,保证init_routine()函数在本进程执行过程中仅仅执行一次
*/

/*
函数原型:int pthread_join(pthread_t thread, void **retval);
功能:以阻塞的方式【!!!等待】thread指定的线程结束。当函数返回时,被等待线程的资源被收回。
如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :thread: 线程标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。
*/



pthread_once_t initialized = PTHREAD_ONCE_INIT;
static int count = 0;

void once_routine()
{
    count++;
    printf("enter once_routine in thread:%lu count:%d\n", pthread_self(), count);
}

void* task_func(void* arg)
{
    pthread_t tid = pthread_self();
    int thread_arg = *((int*)(arg));
    printf("task[%d] enter:%lu\n", thread_arg, tid);
    pthread_once(&initialized, once_routine);
    printf("task[%d] exit:%lu\n", thread_arg, tid);

    return NULL;
}

int main(int argc, char *argv[])
{
    int err = 0, i = 0;
    pthread_t threads[NUM_THREADS];
    int thread_index[NUM_THREADS];

    for(; i<NUM_THREADS; i++)
    {
        printf("Create thread %d\n", i);
        thread_index[i] = i;
        err = pthread_create(&threads[i], NULL, (void*)task_func, &thread_index[i]);
        if(0 != err)
        {
            printf("Fail to create thread\n");
            return -1;
        }
    }

    sleep(5);
    printf("exit main\n");

    for(i=0; i<NUM_THREADS; i++)
    {
        pthread_join(threads[i], NULL);
    }
    return 0;
}

通过gcc -g test_pthread_once.c -o test_pthread_once -lpthread编译后运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值