多线程之间的通信方式
三种专门用于线程同步的机制:POSIX信号量,互斥量和条件变量.
POSIX信号量
在Linux上信号量API有两组,一组是System V IPC信号量,即PV操作,另外就是POSIX信号量,POSIX信号量的名字都是以sem_开头.
#include<semaphore.h>
int sem_init(sem_t* sem,int phshared,unsigned int value);
//初始化一个未命名的信号量
phshared参数指定信号量的类型,若其值为0,就表示这个信号量是当前进程的局部信号量,否则该信号量可以在多个进程之间共享.value值指定信号量的初始值,一般与下面的sem_wait函数相对应.
int sem_destroy(sem_t* sem);
//销毁信号量
int sem_wait(sem_t* sem);
//相当于加锁操作
Int sem_trywait(sem_t* sem);
//相当于尝试加锁
int sem_post(sen_t* sem);
//相当于解锁
其中比较重要的函数sem_wait函数会以原子操作的方式将信号量的值减一,如果信号量的值为零,则sem_wait将会阻塞,信号量的值可以在sem_init函数中的value初始化;sem_trywait函数是sem_wait的非阻塞版本;sem_post函数将以原子的操作对信号量加一,当信号量的值大于0时,其他正在调用sem_wait等待信号量的线程将被唤醒.
这些函数成功时返回0,失败则返回-1并设置errno.
生产者消费者模型:
生产者对应一个信号量:sem_t producer;
消费者对应一个信号量:sem_t customer;
sem_init(&producer,2)----生产者拥有资源,可以工作;
sem_init(&customer,0)----消费者没有资源,阻塞;
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>
sem_t producer_s;
sem_t customer_s;
//采用头插法实现数据的共享
typedef struct node
{
int data;
struct node* next;
}Node;
Node* head = NULL;
void* producer(void* arg)
{
while(1)
{
sem_wait(&producer_s); //producer==0时阻塞
Node* node=(Node*)malloc(sizeof(Node));
node->data=rand()%1000;
printf(node->data);
node->next=head;
head=node;
printf("===========producer:%ld,%ld\n",pthread_self(),node->data);
sem_post(&customer_s); //通知消费者
sleep(rand()%5);
}
return NULL;
}
void* customer(void* arg)
{
while(1)
{
sem_wait(&customer_s);
if(head == NULL)
{
printf("hhy");
}
Node* del=head;
head = head->next;
printf("============customer:%d,%ld\n",pthread_self(),del->data);
free(del);
sem_post(&producer_s);
sleep(rand()%5);
}
return NULL;
}
int main(int argc,const char* argv[])
{
pthread_t p;
pthread_t c;
//初始化信号量
sem_init(&producer_s,0,4);
sem_init(&customer_s,0,0);
pthread_create(&p,NULL,producer,NULL);
pthread_create(&c,NULL,customer,NULL);
pthread_join(p,NULL);
pthread_join(c,NULL);
sem_destroy(&producer_s);
sem_destroy(&customer_s);
return 0;
}
互斥锁
在访问公共资源前对互斥量设置(加锁),确保同一时间只有一个线程访问数据,在访问完成后再释放(解锁)互斥量.
互斥锁的运行方式:串行访问共享资源;
信号量的运行方式:并行访问共享资源;
互斥量用pthread_mutex_t数据类型表示,在使用互斥量之前,必须使用pthread_mutex_init函数对它进行初始化,注意,使用完毕后需调用pthread_mutex_destroy.
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
// 两个函数返回值,成功返回0,否则返回错误码
pthread_mutex_init用于初始化互斥锁,mutexattr用于指定互斥锁的属性,若为NULL,则表示默认属性。除了用这个函数初始化互斥所外,还可以用如下方式初始化:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER。
pthread_mutex_destroy用于销毁互斥锁,以释放占用的内核资源,销毁一个已经加锁的互斥锁将导致不可预期的后果。
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
// 成功返回0,否则返回错误码
pthread_mutex_lock以原子操作给一个互斥锁加锁。如果目标互斥锁已经被加锁,则pthread_mutex_lock则被阻塞,直到该互斥锁占有者把它给解锁.
pthread_mutex_trylock和pthread_mutex_lock类似,不过它始终立即返回,而不论被操作的互斥锁是否加锁,是pthread_mutex_lock的非阻塞版本.当目标互斥锁未被加锁时,pthread_mutex_trylock进行加锁操作;否则将返回EBUSY错误码。注意:这里讨论的pthread_mutex_lock和pthread_mutex_trylock是针对普通锁而言的,对于其他类型的锁,这两个加锁函数会有不同的行为.
pthread_mutex_unlock以原子操作方式给一个互斥锁进行解锁操作。如果此时有其他线程正在等待这个互斥锁,则这些线程中的一个将获得它.
三个打印机轮流打印:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t g_mutex;
int g_cnt = 0;
int loop = 2; //全局变量三个线程之间共享
void *func(void *arg)
{
// int result = *(int*)arg;
long result = (long)arg;
while (loop > 0) {
if (g_cnt % 3 == result) {
switch (result)
{
case 0: {
printf("--- a\n");
break;
}
case 1: {
printf("--- b\n");
break;
}
case 2: {
printf("--- c\n");
break;
}
default: {
return NULL;
}
}
pthread_mutex_lock(&g_mutex);
g_cnt++;
loop--;
pthread_mutex_unlock(&g_mutex);
}
}
return NULL;
}
int main(int argc, char **argv)
{
pthread_t t1, t2, t3;
pthread_mutex_init(&g_mutex, NULL);
pthread_create(&t1, NULL, func, (void *)0);
pthread_create(&t2, NULL, func, (void *)1);
pthread_create(&t3, NULL, func, (void *)2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
return 0;
}
输出结果:
--- a
--- b
--- c
条件变量
如果说互斥锁是用于同步线程对共享数据的访问的话,那么条件变量就是用于在线程之间同步共享数据的值.条件变量提供了一种线程之间通信的机制:当某个共享数据达到某个值时,唤醒等待这个共享数据的线程.
条件变量会在条件不满足的情况下阻塞线程.且条件变量和互斥量一起使用,允许线程以无竞争的方式等待特定的条件发生.
#include<pthread.h>
pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); //初始化条件变量,attr属性参数一般设置为NULL
pthread_cond_destroy(pthread_cont_t *cond); //销毁条件变量
// 成功返回0,否则返回错误码
#include<pthread.h>
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);//通知线程解除阻塞等待
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
// 阻塞等待
其中pthread_cond_broadcast函数以广播的形式唤醒所有等待目标条件变量的线程,pthread_cond_signal函数用于唤醒一个等待目标条件变量线程.但有时候我们可能需要唤醒一个固定的线程,可以通过间接的方法实现:定义一个能够唯一标识目标线程的全局变量,在唤醒等待条件变量的线程前先设置该变量为目标线程,然后采用广播的方式唤醒所有等待的线程,这些线程被唤醒之后都检查该变量以判断是否是自己.
采用条件变量+互斥锁实现生产者消费者模型:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<pthread.h>
//链表
typedef struct node
{
int data;
struct node* next;
}Node;
//定义指针指向链表的头部
Node* head=NULL;
//线程同步 互斥锁
pthread_mutex_t mutex;
//阻塞线程 条件变量
pthread_cond_t cond;
void* producer(void* arg)
{
while(1)
{
Node* pnew=(Node*)malloc(sizeof(Node));
//节点初始化
pnew->data=rand()%1000; //随机数加入队列
//使用了共享数据head 加锁
pthread_mutex_lock(&mutex);
pnew->next=head;
head=pnew;
printf("===========producer:%ld,%ld\n",pthread_self(),pnew->data);
pthread_mutex_unlock(&mutex);
//通知消费者接触阻塞,条件变量
pthread_cond_signal(&cond);
sleep(rand()%3);
}
return NULL;
}
void* customer(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(head==NULL)
{ //线程阻塞
pthread_cond_wait(&cond,&mutex); //条件变量
}
//链表不为空,则删除一个节点
Node* pdel=head;
head=head->next;
printf("=========customer %ld,%ld\n",pthread_self(),pdel->data);
free(pdel);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc,const char* argv[]){
pthread_t p1;
pthread_t p2;
//初始化
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
//创建生产者线程
pthread_create(&p1,NULL,producer,NULL);
//创建消费者线程
pthread_create(&p2,NULL,customer,NULL);
//阻塞,资源回收
pthread_join(p1,NULL);
pthread_join(p2,NULL);
//释放互斥锁的资源
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
运行结果:
===========producer:139883611928320,383
=========customer 139883603535616,383
===========producer:139883611928320,777
=========customer 139883603535616,777
===========producer:139883611928320,793
=========customer 139883603535616,793
===========producer:139883611928320,386
=========customer 139883603535616,386
===========producer:139883611928320,649
=========customer 139883603535616,649
阻塞队列+生产者消费者
#include <iostream>
#include <pthread.h>
#include <queue>
#include <stdlib.h>
#include <unistd.h>
class BlockingQueue
{
public:
BlockingQueue():task_()
{
pthread_mutex_init(&mutex_,NULL);
pthread_cond_init(&cond_,NULL);
};
~BlockingQueue()
{
pthread_mutex_destroy(&mutex_);
pthread_cond_destroy(&cond_);
};
void QueueLock() //加锁
{
pthread_mutex_lock(&mutex_);
};
void QueueUnlock() //解锁
{
pthread_mutex_unlock(&mutex_);
};
void PutData(const int& x) //放数据
{
QueueLock();
task_.push(x);
QueueUnlock();
std::cout << "product data:" << x << std::endl;
pthread_cond_signal(&cond_);
};
void TakeData() //拿数据
{
QueueLock();
while(is_empty())
{
pthread_cond_wait(&cond_,&mutex_);
}
int data = task_.front();
task_.pop();
QueueUnlock();
std::cout << "take data:" << data << std::endl;
};
bool is_empty() //是否为空
{
return task_.empty();
};
private:
pthread_mutex_t mutex_;
pthread_cond_t cond_;
std::queue<int> task_;
};
void *producer(void* arg)
{
BlockingQueue *pro_task = (BlockingQueue*)arg; //类型转换
while(true)
{
int data = rand()%100+1;
pro_task->PutData(data);
sleep(1);
}
};
void *customer(void* arg)
{
BlockingQueue *cus_task = (BlockingQueue*)arg;
while(1)
{
cus_task->TakeData();
}
};
int main()
{
BlockingQueue task;
//创建线程
pthread_t pro,cus;
pthread_create(&pro,NULL,producer,(void*)&task);
pthread_create(&cus,NULL,customer,(void*)&task);
pthread_join(pro,NULL);
pthread_join(cus,NULL);
return 0;
}
运行结果:
product data:84
take data:84
product data:87
take data:87
product data:78
take data:78
product data:16
take data:16
product data:94
take data:94
product data:36
take data:36