编译一个简单的多线程程序
#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
好了,系统启动以后,输入hello,看看输出结果吧。这里需要提一下的就是,如果不希望像上次那样输入命令后程序才执行,而的系统启动以后,程序就可以自动运行的话,就修改叫rc的文件,比如这里我们修改vendor/Samsung/s3c44b0/rc,打开看看,是不是都是系统启动以后的命令?好了,把你的hello加到最后一排就可以了。