Linux C 程序 【02】创建线程

1.开发背景

        上一个篇章,基于 RK3568 平台的基础上,运行了最简单的程序,然而我们使用了 Linux 系统,系统自带的多线程特性还是比较重要的,这个篇章主要描述线程的创建。

2.开发需求

设计实验:

        创建一个线程,主程序等待线程运行

3.开发环境

        ubuntu20.04 + RK3568 + Linux4.19.232

4.实现步骤

        关键接口

pthread_create  # 创建线程  
pthread_join    # 等待线程结束

4.1 最简单的线程

4.1.1 测试源码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <pthread.h>

#include "com_save.h"
#include "app_log.h"

#define FILE_PATH_TEST   ("/home/reetoo/log/test")

typedef struct 
{
    /* 线程 */
    pthread_t thread;

}ctrl_t;

static ctrl_t s_ctrl = {0};
static ctrl_t *p = &s_ctrl;

/* 线程函数 */
void* pthread_process(void* arg)
{
    for (int i = 0; i < 3; i++)
    {
        /* code */
        usleep(1000 * 1000);
        alog_info("pthread_process: %d, pid: %d, pthread_self: %ld\r\n", i, getpid(), pthread_self());
    }

    return NULL;
}

/* 主函数 */
int main(int argc, char* argv[])
{
    /* 文件保存初始化 */
    csave_init(FILE_PATH_TEST);

    /* 日志模块初始化 */
    alog_init();

    /* 打印日志 */
    alog_info("i am main, pid: %d, pthread_self: %ld\r\n", getpid(), pthread_self());

    /* 创建线程 */
    pthread_create(&p->thread, NULL, (void*)pthread_process, NULL);

    /* 等待线程结束 */
    pthread_join(p->thread, NULL);

    return 0;
}
4.1.2 测试结果

        进程号相等 12025,线程号不等,测试OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值