3.1线程概述
3.1.1 线程概述
3.1.2 线程和进程区别
3.1.3 线程和进程虚拟地址空间
3.1.4 线程之间共享和非共享资源
3.1.5 NPTL
3.1.6 线程操作
3.1.7 线程属性
3.2创建线程
/*
一般情况下,main函数所在的线程我们称之为主线程(main线程),其余创建的线程称之为子线程。
程序中默认只有一个进程,fork()函数调用一次后,变为2个进程
程序中默认只有一个线程,pthread_create()函数调用,2个线程。
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
- 功能:创建一个子线程
- 参数:
- thread:传出参数,线程创建成功后,子线程的线程ID被写到该变量中。
- attr : 设置线程的属性,一般使用默认值,NULL
- start_routine : 函数指针,这个函数是子线程需要处理的逻辑代码
- arg : 给第三个参数使用,传参
- 返回值:
成功:0
失败:返回错误号。这个错误号和之前errno不太一样。
获取错误号的信息: char * strerror(int errnum);
*/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void * callback(void * arg) {
printf("child thread...\n");
printf("arg value: %d\n", *(int *)arg);
return NULL;
}
int main() {
pthread_t tid;
int num = 10;
// 创建一个子线程
int ret = pthread_create(&tid, NULL, callback, (void *)&num);
if(ret != 0) {
char * errstr = strerror(ret);
printf("error : %s\n", errstr);
}
for(int i = 0; i < 5; i++) {
printf("%d\n", i);
}
sleep(1);
return 0; // exit(0);
}
3.3终止线程
/*
#include <pthread.h>
void pthread_exit(void* retval);
功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
参数:
retval:需要传递一个指针,作为一个返回值,可以在pthread_join()中获取到。
pthread_t pthread_self(void);
功能:获取当前的线程的线程ID
int pthread_equal(pthread_t t1,pthread_t t2);
功能:比较两个线程ID是否相等;
不同的操作系统,pthread_t类型的实现不一样,有的是无符号的长整型,
有的是使用结构体去实现的。
*/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
void* callback(void* arg){
printf("child thread id : %ld\n",pthread_self());
return NULL;//相当于pthread_exit(NULL);
}
int main()
{
//创建子进程
pthread_t tid;
int ret=pthread_create(&tid,NULL,callback,NULL);
if(ret!=0){
char* errstr=strerror(ret);
printf("error : %s\n",errstr);
}
for(int i=0;i<5;i++){
printf("%d\n",i);
}
printf("tid : %ld, main thread id : %ld\n",tid, pthread_self());
pthread_exit(NULL);
return 0;
}
3.4连接已终止的线程
/*
#include <pthread.h>
int pthread_join(pthread_t thread,void **retval);
-功能:等待线程结束(此函数会阻塞),并回收子线程资源,类似进程的wait()函数。
如果线程已经结束,那么该函数会立即返回。
调用一次只能回收一个子线程;一般在主线程中使用。
-参数:
-thread:需要回收的子线程的ID
-retval:接受子线程退出时的返回值
-返回值:
0:成功;
非0:失败,返回的错误号;
*/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void* callback(void* arg){
printf("child thread id : %ld\n",pthread_self());
//sleep(3);
//return NULL;
static int value=10;
pthread_exit((void*)&value);//return (void*)&value;
}
int main()
{
//创建子进程
pthread_t tid;
int ret=pthread_create(&tid,NULL,callback,NULL);
if(ret!=0){
char* errstr=strerror(ret);
printf("error : %s\n",errstr);
}
for(int i=0;i<10;i++){
printf("%d\n",i);
}
printf("tid : %ld, main thread id : %ld\n",tid, pthread_self());
//主线程调用pthread_join()回收子线程的资源
void* thread_retval =NULL;
ret=pthread_join(tid,&thread_retval);
if(ret!=0){
char* errstr=strerror(ret);
printf("error : %s\n",errstr);
}
printf("exit data : %d\n",*(int*)thread_retval);
printf("回收子线程资源成功!\n");
pthread_exit(NULL);
return 0;
}
3.5线程的分离
/*
#include <pthread.h>
int pthread_detach(pthread_t thread);
-功能:分离一个线程。被分离的线程在终止的时候,会自动释放资源返回给系统。
1.不能多次分离,会产生不可预料的行为。
2.不能去连接一个已经分离的线程;若操作,会报错。
-参数:需要分离的线程的ID
-返回值:
成功:0
失败:返回错误号
*/
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
void* callback(void* arg)
{
printf("child thread id : %ld\n",pthread_self());
return NULL;
}
int main()
{
//创建一个子线程
pthread_t tid;
int ret=pthread_create(&tid,NULL,callback,NULL);
if(ret !=0){
char* errstr=strerror(ret);
printf("error1 : %s\n",errstr);
}
//输出子线程和主线程的id
printf("tid : %ld, main thread id : %ld\n",tid, pthread_self());
//设置子线程分离,子线程分离后,子线程结束时对应的资源就不需要主线程释放
pthread_detach(tid);
if(ret !=0){
char* errstr=strerror(ret);
printf("error2 : %s\n",errstr);
}
//设置分离后,对分离的子线程进行连接 pthread_join()
// ret=pthread_join(tid,NULL);
// if(ret !=0){
// char* errstr=strerror(ret);
// printf("error3 : %s\n",errstr);
// }
pthread_exit(NULL);
return 0;
}
3.6线程取消
/*
#inlcude <pthread.h>
int pthread_cancel(pthread_t thread);
-功能:取消线程(让线程终止)
取消某个线程,可以终止某个线程的运行,
但并不是立马终止,而是当子线程执行到一个取消点,线程才会终止。
取消点:系统规定好的一些系统调用,我们可以粗略的理解为从用户到内核区的切换,
这个位置称为取消点。
*/
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
void* callback(void* arg)
{
printf("child thread id : %ld\n",pthread_self());
for(int i=0;i<5;i++){
printf("child : %d\n",i);
}
return NULL;
}
int main()
{
//创建一个子线程
pthread_t tid;
int ret=pthread_create(&tid,NULL,callback,NULL);
if(ret !=0){
char* errstr=strerror(ret);
printf("error1 : %s\n",errstr);
}
//取消线程
pthread_cancel(tid);
for(int i=0;i<5;i++){
printf("main : %d\n",i);
}
pthread_exit(NULL);
return 0;
}
3.7线程属性
/*
int pthread_attr_init(pthread_attr_t *attr);
- 初始化线程属性变量
int pthread_attr_destroy(pthread_attr_t *attr);
- 释放线程属性的资源
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);
- 获取线程分离的状态属性
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
- 设置线程分离的状态属性
*/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void* callback(void* arg){
printf("child thread id : %ld\n",pthread_self());
return NULL;
}
int main()
{
//创建一个线程属性变量
pthread_attr_t attr;
//初始化属性变量
pthread_attr_init(&attr);
//设置属性
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
//创建一个子线程
pthread_t tid;
int ret=pthread_create(&tid,&attr,callback,NULL);
if(ret !=0){
char* errstr =strerror(ret);
printf("error1 : %s\n",errstr);
}
//获取线程的栈的大小
size_t size;
pthread_attr_getstacksize(&attr,&size);
printf("thread stack size : %ld\n",size);
//输出主线程和子线程的id
printf("tid : %ld, main thread id : %ld\n",tid, pthread_self());
//释放线程属性资源
pthread_attr_destroy(&attr);
pthread_exit(NULL);
return 0;
}
【线程使用注意事项】
(1)主线程退出其他线程不退出,主线程应调用pthread_exit
(2) 避免僵尸程
(a)pthread_join
(b)pthread_detach
(c) pthread create指定分离属性
被join线程可能在join函数返回前就释放完自己的所有内存资源,所以不应当返回被回收线程栈中的值;(3)malloc和mmap申请的内存可以被其他线程释放;
(4)应避免在多线程模型中调用fork,除非马上exec,子进程中只有调用fork的线程存在,其他线程t在子进程中均pthread_exit;
5)信号的复杂语义很难和多线程共存,应避免在多线程引入信号机制
3.8线程同步
3.8.1线程同步
◼ 线程的主要优势在于,能够通过全局变量来共享信息。不过,这种便捷的共享是有代价 的:必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程 修改的变量。
◼ 临界区是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作,也就是 同时访问同一共享资源的其他线程不应终断该片段的执行。
◼ 线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进 行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处 于等待状态。
sellticket.c
/*
使用多线程实现买票的案例。
有3个窗口,一共是100张票。
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局变量,所有的线程都共享这一份资源。
int tickets = 100;
void * sellticket(void * arg) {
// 卖票
while(tickets > 0) {
usleep(6000);
printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
tickets--;
}
return NULL;
}
int main() {
// 创建3个子线程
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
pthread_create(&tid3, NULL, sellticket, NULL);
// 回收子线程的资源,阻塞
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
// 设置线程分离。
// pthread_detach(tid1);
// pthread_detach(tid2);
// pthread_detach(tid3);
pthread_exit(NULL); // 退出主线程
return 0;
}
3.8.2 互斥量
◼ 为避免线程更新共享变量时出现问题,可以使用互斥量(mutex 是 mutual exclusion 的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共 享资源的原子访问。
◼ 互斥量有两种状态:已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一 个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报 错失败,具体取决于加锁时使用的方法。
◼ 一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情 况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问 同一资源时将采用如下协议:
⚫ 针对共享资源锁定互斥量
⚫ 访问共享资源
⚫ 对互斥量解锁
3.8.3 互斥量相关操作函数
◼ 互斥量的类型 pthread_mutex_t
int pthread_mutex_init(pthread_mutex_t * restrict mutex, const pthread_mutexattr_t * restrict attr);
作用: 初始化互斥量
- 参数 :
- mutex : 需要初始化的互斥量变量
- attr : 互斥量相关的属性,NULL
- restrict : C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。
pthread_mutex_t *restrict mutex = xxx;
pthread_mutex_t * mutex1 = mutex; 此时会报错
返回值:返回0,其他任何返回值都表示出现了错误。
int pthread_mutex_destroy(pthread_mutex_t *mutex);
- 释放互斥量的资源
int pthread_mutex_lock(pthread_mutex_t *mutex);
- 加锁,阻塞的,如果有一个线程加锁了,那么其他的线程只能阻塞等待
int pthread_mutex_trylock(pthread_mutex_t *mutex);
- 尝试加锁,如果加锁失败,不会阻塞,会直接返回。
int pthread_mutex_unlock(pthread_mutex_t *mutex);
- 解锁
【互斥锁】
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局变量,所有的线程都共享这一份资源。
int tickets = 1000;
// 创建一个互斥量
pthread_mutex_t mutex;
void * sellticket(void * arg) {
// 卖票
while(1) {
// 加锁
pthread_mutex_lock(&mutex);
if(tickets > 0) { //if只判断一次,不是循环判断!
usleep(6000);
printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
tickets--;
}else {
// 解锁
pthread_mutex_unlock(&mutex);
break;
}
// 解锁
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
// 初始化互斥量
pthread_mutex_init(&mutex, NULL);
// 创建3个子线程
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
pthread_create(&tid3, NULL, sellticket, NULL);
// 回收子线程的资源,阻塞
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
pthread_exit(NULL); // 退出主线程
// 释放互斥量资源
pthread_mutex_destroy(&mutex);
return 0;
}
3.8.4 死锁
【死锁】
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//创建2个互斥量
pthread_mutex_t mutex1,mutex2;
void* workA(void* arg){
pthread_mutex_lock(&mutex1);
sleep(1);
pthread_mutex_lock(&mutex2);
printf("workA...\n");
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return NULL;
}
void* workB(void* arg){
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex1);
printf("workB...\n");
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
return NULL;
}
int main()
{
//初始化互斥量
pthread_mutex_init(&mutex1,NULL);
pthread_mutex_init(&mutex2,NULL);
//创建2个子线程
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,workA,NULL);
pthread_create(&tid2,NULL,workB,NULL);
//回收子线程资源
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
//释放互斥量资源
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
3.8.5 读写锁
◼ 当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其它几个线程也想读取这个共享资源,但是由于互斥锁的排它性,所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。
◼ 在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用。 为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。
◼ 读写锁的特点:
如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作。
如果有其它线程写数据,则其它线程都不允许读、写操作。
写是独占的,写的优先级高。
3.8.6 读写锁相关操作函数
◼ 读写锁的类型 pthread_rwlock_t
◼ int pthread_rwlock_init(pthread_rwlock_t * restrict rwlock, const pthread_rwlockattr_t * restrict attr);
◼ int pthread_rwlock_destroy(pthread_rwlock_t * rwlock);
◼ int pthread_rwlock_rdlock(pthread_rwlock_t * rwlock);
◼ int pthread_rwlock_tryrdlock(pthread_rwlock_t * rwlock);
◼ int pthread_rwlock_wrlock(pthread_rwlock_t * rwlock);
◼ int pthread_rwlock_trywrlock(pthread_rwlock_t * rwlock);
◼ int pthread_rwlock_unlock(pthread_rwlock_t * rwlock);
【读写锁】
/*
读写锁的类型 pthread_rwlock_t
案例:8个线程操作同一个全局变量。
3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 创建一个共享数据
int num = 1;
// pthread_mutex_t mutex;
pthread_rwlock_t rwlock;
void * writeNum(void * arg) {
while(1) {
pthread_rwlock_wrlock(&rwlock);
num++;
printf("++write, tid : %ld, num : %d\n", pthread_self(), num);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
void * readNum(void * arg) {
while(1) {
pthread_rwlock_rdlock(&rwlock);
printf("===read, tid : %ld, num : %d\n", pthread_self(), num);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
int main() {
pthread_rwlock_init(&rwlock, NULL);
// 创建3个写线程,5个读线程
pthread_t wtids[3], rtids[5];
for(int i = 0; i < 3; i++) {
pthread_create(&wtids[i], NULL, writeNum, NULL);
}
for(int i = 0; i < 5; i++) {
pthread_create(&rtids[i], NULL, readNum, NULL);
}
// 设置线程分离
for(int i = 0; i < 3; i++) {
pthread_detach(wtids[i]);
}
for(int i = 0; i < 5; i++) {
pthread_detach(rtids[i]);
}
pthread_exit(NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}
3.8.7 生产者消费者模型
/*
生产者消费者模型(粗略的版本)
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
// 创建一个互斥量
pthread_mutex_t mutex;
struct Node{
int num;
struct Node *next;
};
// 头结点
struct Node * head = NULL;
void * producer(void * arg) {
// 不断的创建新的节点,添加到链表中
while(1) {
pthread_mutex_lock(&mutex);
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->next = head;
head = newNode;
newNode->num = rand() % 1000;
printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
pthread_mutex_unlock(&mutex);
usleep(100);
}
return NULL;
}
void * customer(void * arg) {
while(1) {
pthread_mutex_lock(&mutex);
// 保存头结点的指针
struct Node * tmp = head;
// 判断是否有数据
if(head != NULL) {
// 有数据
head = head->next;
printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
free(tmp);
pthread_mutex_unlock(&mutex);
usleep(100);
} else {
// 没有数据
pthread_mutex_unlock(&mutex);
}
}
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL);
// 创建5个生产者线程,和5个消费者线程
pthread_t ptids[5], ctids[5];
for(int i = 0; i < 5; i++) {
pthread_create(&ptids[i], NULL, producer, NULL);
pthread_create(&ctids[i], NULL, customer, NULL);
}
for(int i = 0; i < 5; i++) {
pthread_detach(ptids[i]);
pthread_detach(ctids[i]);
}
while(1) {
sleep(10);
}
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
return 0;
}
3.8.8 条件变量
条件变量概述:
与互斥锁不同,条件变量是用来等待而不是用来上锁的,条件变量本身不是锁!
条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。
条件变量的两个动作:
--条件不满阻塞线程e
--当条件满足,通知阻塞的线程开始工作
◼条件变量的类型: pthread_cond_t
◼ 条件变量的类型 pthread_cond_t
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
----------------------------------------------------------------------------------------------------------------
int pthread_cond_destroy(pthread_cond_t *cond);
----------------------------------------------------------------------------------------------------------------
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
- 等待;调用了该函数,线程会阻塞。
功能:
阻塞等待一个条件变量
(a) 阻塞等待条件变量cond (参1) 满足
(b)释放已掌握的互斥锁 (解锁互斥量)相当于pthread_mutex_unlock(&mutex);
(a)(b)两步为一个原子操作。
(c) 当被唤醒,pthread_cond_wait函数返回时,解除阻塞并重新申请获取互斥锁pthread mutex_lock(&mutex):参数:
cond:指向要初始化的条件变量指针
mutex:互锁返回值:
成功:0
失败:非0错误号----------------------------------------------------------------------------------------------------------------
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
- 等待多长时间;调用了这个函数,线程会阻塞,直到指定的时间结束。
功能:
限时等待一个条件变量
参数:
cond:指向要初始化的条件变量指针mutex:互斥锁
abstime:绝对时间
返回值:
成功:0
失败:非0错误号************************
abstime补充说明:
struct timespec{
time_t tv_sec; // seconds 秒long tv_usec; // nanosecondes 纳秒
}
time_t cur = time(NULL); //获取当前时间。
struct timespec t; //定义timespec 结构体变量t
t.tv_sec = cur + 1; //定时1秒
pthread_cond timedwait(&cond,&t);----------------------------------------------------------------------------------------------------------------
int pthread_cond_signal(pthread_cond_t *cond);
功能:
唤醒至少一个阻塞在条件变量上的线程
参数:
cond: 指向要初始化的条件变量指针返回值:
成功:0
失败:非0错误号
----------------------------------------------------------------------------------------------------------------
int pthread_cond_broadcast(pthread_cond_t *cond);
功能:
唤醒全部阻塞在条件变量上的线程
参数:
cond: 指向要初始化的条件变量指针返回值:
成功:0
失败:非0错误号
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
// 创建一个互斥量
pthread_mutex_t mutex;
// 创建条件变量
pthread_cond_t cond;
struct Node{
int num;
struct Node *next;
};
// 头结点
struct Node * head = NULL;
void * producer(void * arg) {
// 不断的创建新的节点,添加到链表中
while(1) {
pthread_mutex_lock(&mutex);
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->next = head;
head = newNode;
newNode->num = rand() % 1000;
printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
// 只要生产了一个,就通知消费者消费
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
usleep(100);
}
return NULL;
}
void * customer(void * arg) {
while(1) {
pthread_mutex_lock(&mutex);
// 保存头结点的指针
struct Node * tmp = head;
// 判断是否有数据
if(head != NULL) {
// 有数据
head = head->next;
printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
free(tmp);
pthread_mutex_unlock(&mutex);
usleep(100);
} else {
// 没有数据,需要等待
//当这个函数调用阻塞的时候,会对互斥锁进行解锁,当不阻塞的,继续向下执行,会重新加锁。
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
}
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
// 创建5个生产者线程,和5个消费者线程
pthread_t ptids[5], ctids[5];
for(int i = 0; i < 5; i++) {
pthread_create(&ptids[i], NULL, producer, NULL);
pthread_create(&ctids[i], NULL, customer, NULL);
}
for(int i = 0; i < 5; i++) {
pthread_detach(ptids[i]);
pthread_detach(ctids[i]);
}
while(1) {
sleep(10);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return 0;
}
3.8.9 信号量
信号量的概述:
信号量广泛用于进程或线程间的同步和互斥,信号量本质上是一个非负的整数计数器,它被用来控制对公共资源的访问。
编程时可根据操作信号量值的结果判断是否对公共资源具有访问的权限,当信号量值大于0 时,则可以访问,否则将阻塞。
PV原语是对信号量的操作,一次P操作使信号量减1,一次V操作使信号量加1。
信号量主要用于进程或线程间的同步和互斥这两种典型情况。
信号量用于互斥:
信号量用于同步:
#include <semaphore.h>
◼ 信号量的类型 sem_t
int sem_init(sem_t *sem, int pshared, unsigned int value);
功能:
创建一个信号量并初始化它的值。一个无名信号量在被使用前必须先初始化;
参数:
- sem : 信号量变量的地址
- pshared : 0 用在线程间 ,非0 用在进程间
- value : 信号量中的初始值
返回值:
成功:0
失败:-1
----------------------------------------------------------------------------------------------------------------
信号量P操作(减1)
int sem_wait(sem_t *sem);
- 对信号量加锁,调用一次对信号量的值-1,如果值为0,就阻塞
功能:
将信号量的值减 1。操作前,先检查信号量 (sem)的值是否为0,若信号量为 0,此函数会阻塞,直到信号量大于0时才进行减1操作。
参数:
sem: 信号量的地址返回值:
成功:0
失败:-1
----------------------------------------------------------------------------------------------------------------
int sem_trywait(sem_t *sem);
-以非阻塞的方式来对信号量进行减1操作
-若操作前,信号量的值等于0,则对信号量的操作失败,函数立即返回。----------------------------------------------------------------------------------------------------------------
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
-限时尝试将信号量的值减 1
-abs_timeout: 绝对时间----------------------------------------------------------------------------------------------------------------
信号量V操作(加1)
int sem_post(sem_t *sem);
- 对信号量解锁,调用一次对信号量的值+1
功能:
将信号量的值加1并发出信号唤醒等待线程 (sem_wait())。
参数:
sem: 信号量的地址返回值:
成功:0
失败:-1----------------------------------------------------------------------------------------------------------------
int sem_getvalue(sem_t *sem, int *sval);
功能:
获取 sem 标识的信号量的值,保存在 sva1 中参数:
sem: 信号量地址sva1: 保存信号量值的地址.返回值:
成功:0
失败:-1----------------------------------------------------------------------------------------------------------------
int sem_destroy(sem_t *sem);
- 释放资源
----------------------------------------------------------------------------------------------------------------
sem_t psem;
sem_t csem;
init(psem, 0, 8);
init(csem, 0, 0);producer() {
sem_wait(&psem);
sem_post(&csem)
}customer() {
sem_wait(&csem);
sem_post(&psem)
}----------------------------------------------------------------------------------------------------------------
struct timespec {
time_t tv_sec; // seconds 秒tv_nsec; //nanosecondes 纳秒
};
time_t cur = time(NULL); //获取当前时间
struct timespec t; //定义timespec 结构体变量t
t.tv sec = cur + 1; //定时1秒
sem_timedwait(&cond,&t);
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
// 创建一个互斥量
pthread_mutex_t mutex;
// 创建两个信号量
sem_t psem;
sem_t csem;
struct Node{
int num;
struct Node *next;
};
// 头结点
struct Node * head = NULL;
void * producer(void * arg) {
// 不断的创建新的节点,添加到链表中
while(1) {
sem_wait(&psem);
pthread_mutex_lock(&mutex);
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->next = head;
head = newNode;
newNode->num = rand() % 1000;
printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
pthread_mutex_unlock(&mutex);
sem_post(&csem);
}
return NULL;
}
void * customer(void * arg) {
while(1) {
sem_wait(&csem);
pthread_mutex_lock(&mutex);
// 保存头结点的指针
struct Node * tmp = head;
head = head->next;
printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
free(tmp);
pthread_mutex_unlock(&mutex);
sem_post(&psem);
}
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL);
sem_init(&psem, 0, 8);
sem_init(&csem, 0, 0);
// 创建5个生产者线程,和5个消费者线程
pthread_t ptids[5], ctids[5];
for(int i = 0; i < 5; i++) {
pthread_create(&ptids[i], NULL, producer, NULL);
pthread_create(&ctids[i], NULL, customer, NULL);
}
for(int i = 0; i < 5; i++) {
pthread_detach(ptids[i]);
pthread_detach(ctids[i]);
}
while(1) {
sleep(10);
}
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
return 0;
}