0
点赞
收藏
分享

微信扫一扫

嵌入式Linux 下用户程序实现多任务的方法:多线程的实现


在嵌入式Linux下如何实现用户程序的多任务呢?可以用多线程来实现。


注意:如果线程创建后,主函数应该为一个while(1)的循环,而不能退出,否则,所有的线程全部退出了。。。


也就是主函数不能返回。




测试程序如下:


/*thread.c*/
#include <stdio.h>
#include <pthread.h>

/*线程1*/
void thread_1(void)
{
while(1)
{
printf("thread 1 running!\n");
sleep(1);
}
}

/*线程2*/
void thread_2(void)
{
while(1)
{
printf("thread 2 running!\n");
sleep(1);
}
}
/*线程3*/
void thread_3(void)
{
while(1)
{
printf("thread 3 running!\n");
sleep(1);
}
}

/*线程4*/
void thread_4(void)
{
while(1)
{
printf("thread 4 running!\n");
sleep(1);
}
}

int main(void)
{
pthread_t id_1,id_2,id_3,id_4;
int i,ret;
printf("thread test!!!\n");

/*创建线程一*/
ret=pthread_create(&id_1,NULL,(void *) thread_1,NULL);
if(ret!=0)
{
printf("Create pthread 1 error!\n");
return -1;
}
else
{
printf("thread 1 OK!\n");
}

/*创建线程二*/
ret=pthread_create(&id_2,NULL,(void *) thread_2,NULL);
if(ret!=0)
{
printf("Create pthread 2 error!\n");
return -1;
}
else
{
printf("thread 2 OK!\n");
}

/*创建线程三*/
ret=pthread_create(&id_3,NULL,(void *) thread_3,NULL);
if(ret!=0)
{
printf("Create pthread 3 error!\n");
return -1;
}
else
{
printf("thread 3 OK!\n");
}

/*创建线程四*/
ret=pthread_create(&id_4,NULL,(void *) thread_4,NULL);
if(ret!=0)
{
printf("Create pthread 4 error!\n");
return -1;
}
else
{
printf("thread 4 OK!\n");
}

while(1)
{
sleep(1); //do something or delay
printf("main thread!\n");
}

return 0;
}



Makefile文件如下:



all:
gcc thread.c -o thread_test -lpthread
clean:
rm -rf thread_test *.o



arm Linux下的需要交叉编译器编译:


all:
arm-none-linux-gnueabi-gcc thread.c -o thread_test -lpthread
clean:
rm -rf thread_test *.o




运行效果如下:

嵌入式Linux 下用户程序实现多任务的方法:多线程的实现_主函数


    各个任务交替的运行,因为延时是一样的,次序,可能一致,也可能不一致!!

    可能还有优先级或是调度的问题,每个任务都是while(1)的死循环,因此,实现了简单的多任务(独立的任务)的实现。
至于多任务间的通信,还需要进一步实现。



举报

相关推荐

0 条评论