主题
生产者-消费者(互斥锁 + 条件变量)
cpp
// ============================================================
// EXP-03 V1:生产者-消费者(互斥锁 + 条件变量)
// 编译:g++ -O2 -std=c++17 -pthread -o pc_mutex_cond pc_mutex_cond.cpp
// ============================================================
#include <bits/stdc++.h>
#include <pthread.h>
using namespace std;
static const int CAP = 1024;
static int N = 1000000;
static int buf[CAP], head_, tail_, cnt_;
static long long sum;
static bool done_;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
static pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
static void *producer(void *arg)
{
// 生成线程开始生产
for (int v = 0; v < N; v++) {
pthread_mutex_lock(&m);
while (cnt_ == CAP)
pthread_cond_wait(¬_full, &m);
buf[tail_] = v;
tail_ = (tail_ + 1) % CAP;
cnt_++;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&m);
}
// 通知消费者生产完成
pthread_mutex_lock(&m);
done_ = true;
pthread_cond_broadcast(¬_empty);
pthread_mutex_unlock(&m);
return NULL;
}
static void *consumer(void *arg)
{
long long s = 0;
while (true) {
pthread_mutex_lock(&m);
while (cnt_ == 0 && !done_)
pthread_cond_wait(¬_empty, &m);
if (cnt_ == 0 && done_) {
pthread_mutex_unlock(&m);
break;
}
int v = buf[head_];
head_ = (head_ + 1) % CAP;
cnt_--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&m);
s += v;
}
sum = s;
return NULL;
}
int main(int argc, char **argv)
{
auto t0 = chrono::steady_clock::now();
pthread_t p, c;
pthread_create(&p, NULL, producer, NULL);
pthread_create(&c, NULL, consumer, NULL);
pthread_join(p, NULL);
pthread_join(c, NULL);
double sec = chrono::duration<double>(chrono::steady_clock::now() - t0).count();
printf("V1 mutex+cond: %.3f s, %.0f 条/s, sum=%lld\n",
sec, N / sec, sum);
return 0;
}
// ============================================================
// EXP-03 V2:生产者-消费者(POSIX 信号量)
// 编译:g++ -O2 -std=c++17 -pthread -o pc_semaphore pc_semaphore.cpp
// 注:生产、消费者都只有一个线程,所以函数栈里的数据线程安全
// ============================================================
#include <semaphore.h>
static const int CAP = 1024;
static int N = 1000000;
static int buf[CAP], head_, tail_;
static long long sum;
static sem_t empty_sem, full_sem;
static void *producer(void *arg)
{
for (int v = 0; v < N; v++) {
sem_wait(&empty_sem);
buf[tail_] = v;
tail_ = (tail_ + 1) % CAP;
sem_post(&full_sem);
}
// 写入依旧保证缓冲区不满
sem_wait(&empty_sem);
buf[tail_] = -1; // 结束符
tail_ = (tail_ + 1) % CAP;
sem_post(&full_sem);
return NULL;
}
static void *consumer(void *arg)
{
long long s = 0;
while (true) {
sem_wait(&full_sem);
int v = buf[head_];
head_ = (head_ + 1) % CAP;
sem_post(&empty_sem);
if (v == -1)
break;
s += v;
}
sum = s;
return NULL;
}
int main(int argc, char **argv)
{
sem_init(&empty_sem, 0, CAP);
sem_init(&full_sem, 0, 0);
auto t0 = chrono::steady_clock::now();
pthread_t p, c;
pthread_create(&p, NULL, producer, NULL);
pthread_create(&c, NULL, consumer, NULL);
pthread_join(p, NULL);
pthread_join(c, NULL);
double sec = chrono::duration<double>(chrono::steady_clock::now() - t0).count();
printf("V2 semaphore: %.3f s, %.0f 条/s, sum=%lld\n",
sec, N / sec, sum);
sem_destroy(&empty_sem);
sem_destroy(&full_sem);
return 0;
}
// ============================================================
// EXP-03 V3:生产者-消费者(多生产者 + 多消费者,mutex + cond)
// 编译:g++ -O2 -std=c++17 -pthread -o pc_mpmc pc_mpmc.cpp
// ============================================================
static const int CAP = 1024;
static const int N_PER_PRODUCER = 1000000;
static const int num_produces = 2;
static const int num_consumers = 4;
static int buf[CAP], head_, tail_, cnt_;
static long long sum;
static bool done_;
static int finished_producers;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
static pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
static void *producer(void *arg)
{
(void)arg; // 消 unused 警告
for (int v = 0; v < N_PER_PRODUCER; v++) {
pthread_mutex_lock(&m);
while (cnt_ == CAP)
pthread_cond_wait(¬_full, &m);
buf[tail_] = v;
tail_ = (tail_ + 1) % CAP;
cnt_++;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&m);
}
// 最后一个生产者退出时设 done_,广播唤醒所有消费者
pthread_mutex_lock(&m);
if (++finished_producers == num_produces)
done_ = true;
pthread_cond_broadcast(¬_empty);
pthread_mutex_unlock(&m);
return NULL;
}
static void *consumer(void *arg)
{
(void)arg;
long long s = 0;
while (true) {
pthread_mutex_lock(&m);
while (cnt_ == 0 && !done_)
pthread_cond_wait(¬_empty, &m);
if (cnt_ == 0 && done_) { // 生产结束且缓冲区空 -> 退出
pthread_mutex_unlock(&m);
break;
}
int v = buf[head_];
head_ = (head_ + 1) % CAP;
cnt_--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&m);
s += v;
}
pthread_mutex_lock(&m);
sum += s; // 多消费者累加,锁保护
pthread_mutex_unlock(&m);
return NULL;
}
int main()
{
auto t0 = chrono::steady_clock::now();
vector<pthread_t> ps(num_produces), cs(num_consumers);
for (auto &t : cs) pthread_create(&t, NULL, consumer, NULL); // 先起消费者
for (auto &t : ps) pthread_create(&t, NULL, producer, NULL);
for (auto &t : ps) pthread_join(t, NULL);
for (auto &t : cs) pthread_join(t, NULL);
double sec = chrono::duration<double>(
chrono::steady_clock::now() - t0).count();
long long total = (long long)num_produces * N_PER_PRODUCER;
long long expect = (long long)num_produces
* N_PER_PRODUCER * (N_PER_PRODUCER - 1) / 2;
printf("V3 mutex+cond MPMC: %.3f s, %.0f 条/s, sum=%lld -> %s\n",
sec, total / sec, sum, sum == expect ? "OK" : "FAIL");
return sum == expect ? 0 : 1;
}