生产者消费者模型主要有以下函数和对象
//线程锁对象
pthread_mutex_t mutex;
//用于初始化pthread_mutex_t锁对象
pthread_mutex_init(&mutex, NULL);
//用于销毁pthread_mutex_t锁对象
pthread_mutex_destroy(&mutex)
//线程条件对象
pthread_cond_t cond;
//用于初始化pthread_cond_t线程条件对象
pthread_cond_init(&cond, NULL);
//用于销毁pthread_cond_t线程条件对象
pthread_cond_destroy(&cond);
//用于上锁mutex,本线程上锁后的其他变量是不能
被别的线程操作
pthread_mutex_lock(&mutex);
//用于解锁mutex,解锁后的其他变量可以被其他线程操作
pthread_mutex_unlock(&mutex);
//用于发出条件信号
pthread_cond_signal(&cond);
//用于线程阻塞等待,直到pthread_cond_signal发出条件信号后
才执行退出线程阻塞执行后面的操作
pthread_cond_wait(&cond, &mutex);
示例代码如下:
#include "pthread.h"
#include "queue"
#include "unistd.h"
pthread_t produc;
pthread_t custom;
pthread_mutex_t mutex;
pthread_cond_t cond;
std::queue<int> queue;
void *producCallback(void *data)
{
while (1)
{
pthread_mutex_lock(&mutex);
queue.push(1);
LOGD("生产者生产一个产品,通知消费者消费, 产品数量为 %d", queue.size());
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(5);
}
pthread_exit(&produc);
}
void *customCallback(void *data)
{
while (1)
{
pthread_mutex_lock(&mutex);
if(queue.size() > 0)
{
queue.pop();
LOGD("消费者消费产品,产品数量还剩余 %d ", queue.size());
} else{
LOGD("没有产品可以消费, 等待中...");
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
usleep(500 * 1000);
}
pthread_exit(&custom);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_zzw_jnithread_ThreadDemo_mutexThread(JNIEnv *env, jobject instance) {
for(int i = 0; i < 10; i++)
{
queue.push(1);
}
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&produc, NULL, producCallback, NULL);
pthread_create(&custom, NULL, customCallback, NULL);
}
网友评论