Linux C 程序 【02】创建线程

发布于:2024-06-28 ⋅ 阅读:(141) ⋅ 点赞:(0)

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


网站公告

今日签到

点亮在社区的每一天
去签到