Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

刘淇 #5

Open
qindigo opened this issue Nov 29, 2023 · 0 comments
Open

刘淇 #5

qindigo opened this issue Nov 29, 2023 · 0 comments

Comments

@qindigo
Copy link

qindigo commented Nov 29, 2023

#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();
	}


}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant