找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 13|回复: 0

主线程序独立运行无限循环, 子线程给发动机点火再回来

[复制链接]

30

主题

26

回帖

4万

积分

管理员

积分
42068
发表于 2025-2-28 14:35:53 | 显示全部楼层 |阅读模式
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

// 线程函数,用于输出高低电平,运行3次循环
void* thread_function(void* arg) {
    int loop_count = 0;  // 循环计数器

    while (loop_count < 3) {  // 只运行3次循环
        // 输出1秒低电平
        printf("Low level (1s)\n");
        sleep(1);

        // 输出3秒高电平
        printf("High level (3s)\n");
        sleep(3);

        loop_count++;  // 增加循环计数
    }

    printf("Thread finished its task.\n");
    return NULL;
}

// 被调用的函数,用于创建线程并执行任务
void start_thread() {
    pthread_t thread;
    int ret;

    // 创建线程
    ret = pthread_create(&thread, NULL, thread_function, NULL);
    if (ret != 0) {
        fprintf(stderr, "Error creating thread\n");
        exit(EXIT_FAILURE);
    }

    // 将线程设置为分离状态,线程结束后自动回收资源
    pthread_detach(thread);
}

// 主函数
int main() {
    // 调用函数,启动线程
    start_thread();

    // 主进程不断打印 "dog"
    while (1) {
        printf("dog\n");
        sleep(1);  // 每隔1秒打印一次
    }

    return 0;
}
我知道答案 回答被采纳将会获得 10 金钱 已有0人回答
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|flightreview|小黑屋|PX4-Autopilot|PX4论坛

GMT+8, 2025-3-12 19:08 , Processed in 0.070808 second(s), 24 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表