(本节笔记的实验代码,在这里)
/* 切记!在编译pthread的多线程程序时,必须在末尾加上 -lpthread 选项,对,是要在末尾!如:gcc send.c -o send -lpthread */
1. 线程基本概念
线程与创建它的进程共享代码段和数据段,并拥有自己独立的栈,是“轻量级”的进程。
2. 函数学习
2.1 创建线程
函数名:
pthread_create
函数原型: man pthread_create
intpthread_create(pthread_t *thread, const pthread_attr *attr, void*(*start_routine) (void *), void *arg);
函数功能:
创建新的线程。
所属头文件:
<pthread.h> /*链接是需加“ -lpthread ” */
返回值:
成功:返回0 失败 :返回错误编号
参数说明:
thread:保存新创建的线程ID的指针。
attr:线程属性,一般设NULL,Liunx自动设置属性。
start_routine:线程的入口函数指针。线程创建后,从该函数执行。
arg:线程入口函数的参数,一般为NULL。
2.2 等待线程结束
函数名:
pthread_join
函数原型: man pthread_join
intpthread_join(pthread_t thread, void **retval);
函数功能:
等待线程结束。
所属头文件:
<pthread.h> /*链接是需加“ -lpthread */
返回值:
成功:返回0 失败 :返回错误编号
参数说明:
thread:要等待结束的线程ID。
retval:保存线程退出时的状态,一般为NULL。
2.3 退出线程
函数名:
pthread_exit
函数原型: man
voidpthread_exit(void *retval);
函数功能:
结束当前线程。 /*不能直接使用exit(),否则会直接结束整个进程 */
所属头文件:
<pthread.h> /*链接是需加“ -lpthread ” */
返回值:
无返回值。
参数说明
retval:保存线程退出时的状态,一般为NULL。
3. 线程互斥基本概念
多个线程访问同一数据或资源时,为避免线程间相互影响,需要引入线程互斥机制,互斥锁(mutex)为其中一种。
4. 线程互斥函数学习
4.1初始化互斥锁
函数名:
pthread_mutex_init
函数原型: man pthread_mutex_init
intpthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t*restrict attr);
函数功能:
初始化一个互斥锁。 /*pthread_mutex_tmutex = PTHREAD_MUTEX_INITIALIZER(静态初始化) */
所属头文件: <pthread.h>
返回值:
成功:返回0 失败 :返回错误编号
参数说明
mutex:需要初始化的互斥锁指针。
attr:互斥锁属性,一般设NULL,Liunx自动设置属性。
4.2 互斥锁上锁
函数名:
pthread_mutex_lock
函数原型: man pthread_mutex_lock
intpthread_mutex_lock(pthread_mutex_t *mutex);
函数功能:
给mutex所指向的互斥锁上锁。
所属头文件:
<pthread.h>
返回值:
成功:返回0 失败 :返回错误编号
参数说明
mutex:要上锁的互斥锁指针。
4.3 互斥锁解锁
函数名:
pthread_mutex_unlock
函数原型: man pthread_mutex_unlock
intpthread_mutex_unlock(pthread_mutex_t *mutex);
函数功能:
给mutex所指向的互斥锁解锁。
所属头文件:
<pthread.h>
返回值:
成功:返回0 失败 :返回错误编号
参数说明
mutex:要解锁的互斥锁指针。
5.综合实例
/* touch pthread.c */
/* 在主进程中创建两线程,使得number在线程中自增10 */
#include<stdio.h>
#include <pthread.h>
pthread_t thread[2];
int number = 0;
pthread_mutex_t mut;
void * worker1()
{
int i = 0;
printf("I amworker1\n");
for(i = 0; i <10; i++)
{
pthread_mutex_lock(&mut);
number++;
printf("worker1number is %d\n", number);
pthread_mutex_unlock(&mut);
}
pthread_exit(NULL);;
}
void * worker2()
{
int i = 0;
printf("I amworker2\n");
for(i = 0; i <10; i++)
{
pthread_mutex_lock(&mut);
number++;
printf("worker2number is %d\n", number);
pthread_mutex_unlock(&mut);
}
pthread_exit(NULL);;
}
int main()
{
pthread_mutex_init(&mut,NULL);
/* 创建工人1线程 */
pthread_create(&thread[0],NULL, worker1, NULL);
/* 创建工人2线程 */
pthread_create(&thread[1],NULL, worker2, NULL);
/* 等待工人1线程的结束 */
pthread_join(thread[0],NULL);
/* 等待工人2线程的结束 */
pthread_join(thread[1],NULL);
return 0;
}