概述
就像每个进程都有一个进程号一样,每个线程也有一个线程号。进程号在整个系统中是唯一的,,但线程号不同,线程号只在它所属的进程环境中有效。进程号用 pid_t 数据类型表示,是一个非负整数。线程号则用 pthread_t 数据类型来表示,Linux 使用无符号长整数表示。有的系统在实现 pthread_t 的时候,用一个结构体来表示,所以在可移植的操作系统实现不能把它做为整数处理。
线程的常用函数
1)获取线程号
所需头文件:
#include <pthread.h>
pthread_t pthread_self(void);
功能:
获取线程号。
参数:
无
返回值:
调用线程的线程 ID 。
2)线程号的比较
所需头文件:
#include <pthread.h>
int pthread_equal(pthread_t t1, pthread_t t2);
功能:
判断线程号 t1 和 t2 是否相等。为了方便移植,尽量使用函数来比较线程 ID。
参数:
t1,t2:待判断的线程号。
返回值:
相等: 非 0
不相等:0
示例代码:
#include <stdio.h>#include <stdlib.h>#include <pthread.h>int main(int argc, char *argv[]){pthread_t thread_id;thread_id = pthread_self(); // 返回调用线程的线程IDprintf("Thread ID = %lu \n",thread_id);if( 0 != pthread_equal( thread_id, pthread_self() ) ){printf("Equal!\n");}else{printf("Not equal!\n");}return 0;}线程函数的程序在 pthread 库中,故链接时要加上参数 -lpthread。
运行结果如下:
3)线程的创建
所需头文件:
#include <pthread.h>
int pthread_create( pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *),
void *arg );
功能:
创建一个线程。
参数:
thread:线程标识符地址。
attr:线程属性结构体地址,通常设置为 NULL。
start_routine:线程函数的入口地址。
arg:传给线程函数的参数。
返回值:
成功:0
失败:非 0
pthread_create() 创建的线程从指定的回调函数开始运行,该函数运行完后,该线程也就退出了。线程依赖进程存在的,共享进程的资源,如果创建线程的进程结束了,线程也就结束了。
示例一:
#include <stdio.h>#include <unistd.h>#include <pthread.h>int var = 8;void *thread_1(void *arg){while(1){printf("this is my new thread1: var++\n");var++;sleep(1);}return NULL;}void *thread_2(void * arg){while(1){printf("this is my new thread2: var = %d\n", var);sleep(1);}return NULL;}int main(int argc, char *argv[]){pthread_t tid1,tid2;//创建两个线程pthread_create(&tid1, NULL, thread_1, NULL); pthread_create(&tid2, NULL, thread_2, NULL);while(1){printf("the main thread: var = %d\n", var);sleep(1);}return 0;}运行结果如下:
示例二:
#include <stdio.h>#include <unistd.h>#include <pthread.h>// 回调函数void *thread_fun(void * arg){sleep(1);int num = *( (int *)arg );printf("int the new thread: num = %d\n", num);return NULL;}int main(int argc, char *argv[]){pthread_t tid;int test = 100;// 创建线程, 把 &test 传给回调函数 thread_fun()pthread_create(&tid, NULL, thread_fun, (void *)&test);while(1);return 0;}运行结果如下:
4)回收线程资源
所需头文件:
#include <pthread.h>
int pthread_join(pthread_t thread,void **retval);
功能:
等待线程结束(此函数会阻塞),并回收线程资源,类似进程的 wait() 函数。如果线程已经结束,那么该函数会立即返回。
参数:
thread:被等待的线程号。retval:用来存储线程退出状态的指针的地址。
返回值:
成功:0
失败:非 0
只有经历过地狱般的折磨,才有征服天堂的力量,只有流过血的手指,才能弹出世间的绝唱。