生产者与消费者模型:
生产者:生产数据的线程
消费者:使用、处理数据的线程
缓冲区:隔离生产者和消费者,这样可以避免互相等待,提高运行效率。
生产者快于消费者:缓冲区会爆满
消费者快于生产者:缓冲区一直空
使用条件变量可以解决生产者和消费者之间效率不匹配的问题
生产者快于消费者,通知消费者加速消费,生产者睡眠降低生产速度
消费者快于生产者,通知生产者加速生产,消费者睡眠降低消费速度
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#define STORE_SIZE (20)
char store[STORE_SIZE];
int store_cnt = 0;
pthread_mutex_t lock;
pthread_cond_t empty;
pthread_cond_t full;
void show_store(char* op,char data)
{
for(int i=0; i<store_cnt; i++)
{
printf("%c",store[i]);
}
printf(" %s %c\n",op,data);
}
void *producter(void* arg)
{
for(;;)
{
// 加锁保护仓库
pthread_mutex_lock(&lock);
// 判断仓库是否已满
if(store_cnt >= STORE_SIZE)
{
// 叫醒消费者线程
pthread_cond_signal(&empty);
// 生产者进入睡眠
pthread_cond_wait(&full,&lock);
}
// 生产数据
char data = rand()%26 + 'A';
show_store("<-",data);
store[store_cnt++] = data;
// 模拟生产数据消耗时间
usleep(rand()%90000+90000);
// 叫醒消费者
pthread_cond_signal(&empty);
pthread_mutex_unlock(&lock);
}
}
void* consumer(void* arg)
{
for(;;)
{
// 加锁保计仓库
pthread_mutex_lock(&lock);
// 判断仓库是否空
if(store_cnt <= 0)
{
// 叫醒生产者
pthread_cond_signal(&full);
// 消费者睡眠
pthread_cond_wait(&empty,&lock);
}
// 消费数据
char data = store[--store_cnt];
show_store("->",data);
// 模拟消费耗时
usleep(rand()%90000+90000);
pthread_cond_signal(&full);
pthread_mutex_unlock(&lock);
}
}
int main(int argc,const char* argv[])
{
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&empty,NULL);
pthread_cond_init(&full,NULL);
pthread_t tids[10];
for(int i=0; i<10;i++)
{
if(i%2)
pthread_create(&tids[i],NULL,producter,NULL);
else
pthread_create(&tids[i],NULL,consumer,NULL);
}
for(int i=0; i<10; i++)
{
pthread_join(tids[i],NULL);
}
}
线程与socket编程
由于TCP是面向连接的协议,需要一对一通信,需要为每个客户端进行服务,之前是为每个客户端创建一个进程来服务,但创建进程耗费的资源比较多,相较于进程,线程更适合为每个客户端服务
随着客户端的连接和退出,服务端需要频繁的创建、销毁线程,比较耗费时间,如何解决?
信号量:
信号量是一个计数器,与进程间通信使用的信号量原理一样,用于控制访问有限的共享资源
sem_t
int sem_init(sem_t *sem, int pshared, unsigned int value);
功能:初始化信号量
pshared:
一般取0,表示进程内多个线程之间共享使用
非0,该信号量以共享内存方式,让多个进程使用,但是Linux系统不支持
value:信号量的初值,代表资源的个数
int sem_wait(sem_t *sem);
功能:对信号量减一操作,如果不能减则阻塞
int sem_trywait(sem_t *sem);
功能:对信号量尝试减一,如果不能则返回错误
int sem_timedwait(sem_t *sem)
int sem_post(sem_t *sem);
功能:对信号量进行
int sem_destory(sem_t *sem)
进程与线程、协程区别 C没有
进程处理多任务时需要解决什么问题
线程处理多任务时需要解决什么问题
TCP服务端的编程模型有哪几种 优缺点