uclinux下实现多线程[转]
編譯一個簡單的多線程程序
#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加到最后一排就可以了。
總結
以上是生活随笔為你收集整理的uclinux下实现多线程[转]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小白都能看懂 XAMPP的下载安装配置详
- 下一篇: 我的世界怎么做洗衣机(汉典我字的基本解释