点击打开链接
1、pthread_create函数定义
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void), void *restrict arg);
参数1:指向线程标识符指针。
参数2:线程属性。
参数3:线程运行函数起始地址。
参数4:运行函数的参数。
创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。前者表示系统限制创建新的线程,例如线程数目过多了;后者表示第二个参数代表的线程属性值非法。
2、pthread_join函数定义
代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。
3、源码包含pthread头文件
编程实现三个线程ABC,并让它们顺次打印ABC
这里是一道题的两种解法
include <pthread.h>
#include <stdio.h>
#include <iostream>
#include <sys/types.h>
#include <semaphore.h>
#include <pthread.h>
using namespace std;
sem_t sem_id1,sem_id2,sem_id3;
void *func1 (void*) {sem_wait(&sem_id1);printf("A\n");sem_post(&sem_id2);}
void *func2 (void*) {sem_wait(&sem_id2);printf("B\n");sem_post(&sem_id3);}
void *func3 (void*) {sem_wait(&sem_id3);printf("C\n");sem_post(&sem_id1);}
int main(){
sem_init(&sem_id1, 0, 1);
sem_init(&sem_id2, 0, 0);
sem_init(&sem_id3, 0, 0);
pthread_t pthread_id1, pthread_id2, pthread_id3;
pthread_create(&pthread_id1, NULL, func1, NULL);
pthread_create(&pthread_id2, NULL, func2, NULL);
pthread_create(&pthread_id3, NULL, func3, NULL);
pthread_join(pthread_id1, NULL);
cout<<1<<endl;
pthread_join(pthread_id1, NULL);
cout<<2<<endl;
pthread_join(pthread_id1, NULL);
cout<<3<<endl;
return 0;
}
// #include <stdio.h>
// #include <pthread.h>
// void *secondFunc(void *);
// void *thirdFunc(void *);
// void *firstFunc(void *args)
// {
// pthread_t id2;
// pthread_create(&id2,NULL,&secondFunc,NULL);
// pthread_join(id2,NULL);
// printf("C\n");
// }
// void *secondFunc(void *args)
// {
// pthread_t id3;
// pthread_create(&id3,NULL,&thirdFunc,NULL);
// pthread_join(id3,NULL);
// printf("B\n");
// }
// void *thirdFunc(void *args)
// {
// printf("A\n");
// }
// int main()
// {
// pthread_t id1;
// pthread_create(&id1,NULL,&firstFunc,NULL);
// pthread_join(id1,NULL);
// return 0;
// }
4、编译执行多线程程序
编译上述多线程程序,必须使用 -lpthread编译选项,因为pthread库不是Linux默认链接库,链接时必须指定使用libpthread.a库(天缘机子ubuntu11.10这些库在/usr/lib/i386-linux-gnu路径下),在编译选项中需添加-lpthread参数,示例如:
C编译选项:
>gcc test.c -o test -lpthread
C++编译选项:
>g++ ctest.cpp test.cpp -o test -lpthread
如果是写到MAKEFILE中,可以找到类似TARG_OPTIONS=这样的位置添加-lpthread。
但是往往还是会报告pthread_create未声明问题,说明编译器仍未找到libpthead.a的位置,这时可手动在编译命令行中添加:-L./usr/lib/i386-linux-gnu 选项(这里的路径是libthread.a路径,不同系统、机子可能有所不同!!)。
执行:
>./test
cmake写法
ADD_EXECUTABLE(thread thread.cpp)
TARGET_LINK_LIBRARIES(thread -lpthread )
加一个链接 -lpthread