Skip to content

刘淇 #5

Open
Open
@qindigo

Description

@qindigo
#include<iostream>
#include<time.h>
#include<mutex>
#include<condition_variable>
#include<queue>
using namespace std;
void publisher();
void subscriber(int);
mutex mtx_1, mtx_2;
condition_variable g_cv;
queue<int>g_queue;
int main()
{
	thread th1(publisher);
	thread th2(subscriber);
	th1.join();
	th2.join();
	return 0;
}
void publisher()
{
	mtx_1.lock();
	int data = rand() % 100 + 1;
	g_queue.push(data);
	g_cv.notify_one();
	mtx_1.unlock();
}
void subscriber(int p)
{
	while (1)
	{
		mtx_2.lock();
		bool isempty = g_queue.empty();
		g_cv.wait(lock,!isempty );
		int p = g_queue.front();
			if (p % 2 == 0)
			{
				printf("%d", p);
			}
			g_queue.pop();
		mtx_2.unlock();
	}


}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions