在linux嵌入式应用当中,如何创建多线程任务,C语言实现的具体过程

在Linux应用中创建多线程任务通常使用pthread库(POSIX Threads)。下面是一个简单的C语言示例,演示如何在Linux中创建多线程任务:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 5

// 线程函数
void *thread_func(void *thread_id) {
    long tid;
    tid = (long)thread_id;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;

    // 创建多个线程
    for(t = 0; t < NUM_THREADS; t++) {
        printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, thread_func, (void *)t);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    // 等待所有线程结束
    for(t = 0; t < NUM_THREADS; t++) {
        pthread_join(threads[t], NULL);
    }

    printf("All threads completed. Exiting.\n");

    pthread_exit(NULL);
}

上述代码中,我们首先包含了必要的头文件<stdio.h>, <stdlib.h>, 和 <pthread.h>。然后定义了宏NUM_THREADS表示线程的数量。

接着定义了一个线程函数thread_func,它接受一个void*类型的参数,并在函数中将其转换为long类型,然后打印出相应的线程号。该函数是由每个线程执行的实际任务。

main函数中,我们声明了一个pthread_t类型的数组来存放线程的标识符,以及一些变量用于循环和错误检查。在循环中,我们使用pthread_create函数创建了多个线程,并将其与指定的线程函数进行关联。然后,我们使用pthread_join函数等待所有线程执行完毕。

最后,我们打印一条消息表示所有线程已经完成,并退出程序。

要编译这个程序,您可以使用如下命令:

gcc -o multithreading_example multithreading_example.c -lpthread
然后运行生成的可执行文件:
./multithreading_example
会看到输出类似于:
In main: creating thread 0
Hello World! It's me, thread #0!
In main: creating thread 1
Hello World! It's me, thread #1!
In main: creating thread 2
Hello World! It's me, thread #2!
In main: creating thread 3
Hello World! It's me, thread #3!
In main: creating thread 4
Hello World! It's me, thread #4!
All threads completed. Exiting.
这证明了多线程任务已经成功创建并执行

  • 20
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值