信号量实现生产者消费者
int g_num = 0;
std::binary_semaphore semp(1);
std::binary_semaphore sems(0);
void P(int i)
{
for (int i = 0; i < 10; ++i)
{
semp.acquire();
g_num = i;
cout << "P:" << g_num << endl;
sems.release();
}
}
void S()
{
for (int i = 0; i < 20; ++i)
{
sems.acquire();
cout << "S:" << g_num << endl;
semp.release();
}
}
int main()
{
thread tha(P, 1);
thread thc(P, 2);
thread thb(S);
tha.join();
thb.join();
thc.join();
return 0;
}
int g_num = 0;
std::counting_semaphore semp(2);
std::counting_semaphore sems(0);
std::mutex mx;
void P(int i)
{
for (int i = 0; i < 10; ++i)
{
semp.acquire();
mx.lock();
g_num = i;
mx.unlock();
cout << "P:" << g_num << endl;
sems.release();
}
}
void S()
{
for (int i = 0; i < 20; ++i)
{
sems.acquire();
cout << "S:" << g_num << endl;
semp.release();
}
}
int main()
{
thread tha(P, 1);
thread thc(P, 2);
thread thb(S);
tha.join();
thb.join();
thc.join();
return 0;
}
MySemaphore
class MySemaphore
{
public:
MySemaphore(int val = 1):count(val){}
void P()
{
std::unique_lock<std::mutex> lck(mtk);
if (--count < 0)
{
cv.wait(lck);
}
}
void V()
{
std::unique_lock<std::mutex> lck(mtk);
if (++count <= 0)
{
cv.notify_one();
}
}
int get_count()
{
return count;
}
private:
int count;
std::mutex mtk;
std::condition_variable cv;
};
int g_num = 0;
MySemaphore semp(1);
MySemaphore sems(0);
std::mutex mx;
void P(int id)
{
for (int i = 0; i < 10; ++i)
{
semp.P();
mx.lock();
g_num = i;
cout << "生产者:" << " " << g_num << endl;
mx.unlock();
sems.V();
}
}
void S(int id)
{
for (int i = 0; i < 10; ++i)
{
sems.P();
mx.lock();
cout << "消费者: " << ":" << g_num << endl;
mx.unlock();
semp.V();
}
}
int main()
{
std::thread tha(P, 0);
std::thread ths(S, 0);
tha.join();
ths.join();
return 0;
}
- 首先生产者线程进入,对生产者的信号量进行了一次P操作,生产者的信号量Pcount 1 -> 0 ,并且在最后将消费者的信号量Scount由0 -> 1
- 紧接消费者进入线程,进行一次P操作,消费者信号量Scount 1 -> 0,然后生产者的信号量进行一次V操作 Pcount 0 -> 1
- 倘若下一次进入的还是消费者,首先进行一次P操作,那么消费者Scount 0 -> -1 ,则消费者P操作进入等待队列
- 这时消费者的P操作陷入等待队列,只能由生产者进行P操作,则生产者信号量自减 Pcount 1 -> 0,接着将消费者进行V操作 Scount -1 -> 0 ,此时进行一次唤醒,将原本进入等待队列的消费者唤醒
|