1.在nfs目录下创建 thread.c文件
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<sys/ioctl.h>
- #include<pthread.h>
- int task1(int *cnt)
- {
- while(*cnt < 5)
- {
- sleep(1);
- (*cnt) ++;
- printf("task1 cnt = %d./n", *cnt);
- }
- return (*cnt);
- }
- int task2(int* cnt)
- {
- while(*cnt <5)
- {
- sleep(2);
- (*cnt) ++;
- printf("task2 cnt = %d./n", *cnt);
- }
- return (*cnt);
- }
- int main(int argc, char* argv[])
- {
- int result;
- int t1 = 0;
- int t2 = 0;
- int rt1, rt2;
- pthread_t thread1, thread2;
- /* create the first thread.*/
- result = pthread_create(&thread1, PTHREAD_CREATE_JOINABLE, (void*)task1,(void*)&t1 );
- if(result)
- {
- perror("pthread_create: task1./n");
- exit(EXIT_FAILURE);
- }
- //created the second thread
- result = pthread_create(&thread2, PTHREAD_CREATE_JOINABLE,(void*)task2,(void*)&t2 );
- if(result)
- {
- perror("pthread_create:task2./n");
- exit(EXIT_FAILURE);
- }
- pthread_join(thread1, (void *) &rt1);
- pthread_join(thread2, (void *) &rt2);
- printf("total %d time./n", t1*t2);
- printf("return value of task1: %d/n", rt1);
- printf("return value of task2: %d./n", rt2);
- exit(EXIT_SUCCESS);
- }
2.编写makefile文件:
- EXEC = thread
- OBJS = thread.o
- SVR = thread.c
- CC = arm-linux-gcc
- CFLAGS = -o2 -Wall
- DFLAGS += -lpthread
- all:$(EXEC)
- $(EXEC):$(OBJS)
- $(CC) $(DFLAGS) -o $@ $^
- %.o:%.c
- $(CC) $(CFLAGS) -o $@ -c $<
- clean:
- @rm -vf $(EXEC) *.o *~
3.执行make,编译该文件
- [root@wzb test4]# ls
- makefile thread.c
- [root@wzb test4]# make
- arm-linux-gcc -o2 -Wall -o thread.o -c thread.c
- arm-linux-gcc -lpthread -o thread thread.o
- [root@wzb test4]#
4.在超级终端,进行运行测试.
- /mnt/nfs/arm/project/test4 # ls
- makefile thread thread.c thread.o
- /mnt/nfs/arm/project/test4 # ./thread
- task1 cnt = 1.
- task2 cnt = 1.
- task1 cnt = 2.
- task1 cnt = 3.
- task2 cnt = 2.
- task1 cnt = 4.
- task1 cnt = 5.
- task2 cnt = 3.
- task2 cnt = 4.
- task2 cnt = 5.
- total 25 time.
- return value of task1: 5
- return value of task2: 5.
- /mnt/nfs/arm/project/test4 #
测试成功!
注意: 该程序用到多线程库,编译时的连接线程库的选项 -lpthread,是必不可少的!
不然编译通不过! 所以的makefile中的 DFLAGS += -lpthread
呵呵,有学了的编译连接库的选项: -l 。