/first.c 一个最基础的程序*/
1 #include<stdio.h>
2 #include<pthread.h> //一定要包含
3 void thread(void)
4 {
5 int i;
6 for(i =0;i<3;i++)
7 {
8 printf("This is a pthread.\n");
9 sleep(1);
10 }
11 }
12 int main(void)
13 {
14 pthread_t id; // pthread_t在头文件 /usr/include/bits/pthreadtypes.h 中定义;typedef unsigned long int pthread_t;它是一个线程的标识符。
15 int i;
16 int ret;
17 ret = pthread_create(&id,NULL,(void *)thread,NULL);
18 if(ret != 0)
19 {
20 printf("Create pthread error!");
21 return -1;
22 }
23 pthread_detach(id);
24 for(i = 0;i < 3;i++)
25 {
26 printf("This is the main process.\n");
27 sleep(1);
28 }
29
30 return 0;
31 }
linux下运行如下所示:
gcc -lpthread first.c -o first //编译
./first //运行
This is the main process.
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
This is a pthread.
./first
This is the main process.
This is a pthread.
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
前后两次结果不一样,这是两个线程争夺CPU资源的结果。
函数介绍:
函数pthread_create用来创建一个线程,它的原型为:
extern int pthread_create __P ((pthread_t *__thread , __const pthread_attr_t *__attr , void *(*__start_routine) (void *) , void *__arg));
第一个参数为指向线程标识符的指针,
第二个参数用来设置线程属性,
第三个参数是线程运行函数的起始地址,
最后一个参数是运行函数的参数。这里,我们的函数thread不需要参数,所以最后一个参数设为空指针。第二个参数我们也设为空指针,这样将生成默认属性的线程。对线程属性的设定和修改我们将在下一节阐述。当创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。前者表示系统限制创建新的线程,例如线程数目过多了;后者表示第二个参数代表的线程属性值非法。创建线程成功后,新创建的线程则运行参数三和参数四确定的函数,原来的线程则继续运行下一行代码。
线程的退出
在线程的处理函数中,可以显示的调用pthread_exit()结束线程执行,也可以不调用pthread_exit(),而只是让线程处理程序返回。
除了pthread_exit() 函数,可以让当前调用pthread_exit() 的线程显示地退出外,线程也可以使用 pthread_cancel() 函数终止其他线程的执行。
等待线程结束
pthread_join() 函数会挂起创建线程的线程的执行,直到等待到想要等待的子线程。
int pthread_join(pthread_t th, void **thread_return);
线程的分离
主线程创建子线程,且子线程本身自己有自我回收内存资源的能力。
int pthread_detach(pthread_t th);
获得当前线程标志
使用pthread_self() 函数可以获得当前线程的标志,pthread_self() 的返回值就是当前线程的标志。
pthread_t pthread_self(void);