最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

uclinux下实现多线程

XAMPP新闻 admin 262浏览 0评论

本文内容是10年时在FPGA软核NIOS上运行uclinux时从网上收集而来, 原文网址已不可考, 我略加整改而成.

虽是在uclinux下建立多线程的示例, 但在linux下也适用也有参考价值, 套路都一样. 不过uclinux这两年已经很少看到有人谈起了, 硬件发展了资源丰富了, 也不太有必要用uclinux了, 大家且看看吧.

我们这里就不再赘述 进程process 和 线程thread 的概念了, 直接进入正题.

由于uClinux只是Linux的一个子集, 它没有Linux里实现多进程的fork函数, 只有vfork, 但是vfork在建立子进程后得等到子进程运行完才运行父进程, 在使用的时候很不方便.

不过幸好, 它实现了多线程.

一个简单的多线程程序:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
void task(int *counter); //声明线程1
void task2(int *counter); //声明线程2
int gCounter = 0;
int gCounter2 = 0;

int main(void)
{
pthread_t thrd,thrd2;
int result;
fprintf(stderr,"hello world\n");
printf("Thread Demo under uClinux.\n");

result = pthread_create(&thrd,NULL,(void*)task,(void*)&gCounter);
if (result)
{
perror("pthread create fail");
exit(0);
}
result = pthread_create(&thrd2,NULL,(void*)task2,(void*)&gCounter2);
if (result)
{
perror("pthread create fail");
exit(0);
}
pthread_join(thrd,NULL); //等待线程结束
return 0;
}

void task(int *counter)
{
while (*counter <5)
{
printf("hello world from pthread1!\n");
(*counter)++;
sleep(1);
}
}

void task2(int *counter)
{
while ( *counter <2)
{
printf("hello world from pthread2!\n");
(*counter)++;
sleep(2);
}
}

需要注意一点:由于需要多线程, 在代码里我们加入了#include <pthread.h>, 在Makefile里也需要添加一句LDLIBS += -lpthread, 具体如下:

EXEC = hello
OBJS = hello.o
LDLIBS += -lpthread
all: $(EXEC)
$(EXEC): $(OBJS)
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS)
romfs:
$(ROMFSINST) /bin/$(EXEC)
clean:
-rm -f $(EXEC) *.elf *.gdb *.o

好了, 就这么多, 并不麻烦.

转载请注明:XAMPP中文组官网 » uclinux下实现多线程

您必须 登录 才能发表评论!