生产者消费者&队列&单例

这里写目录标题

一级目录

#include<iostream>
#include<mutex>
#include<condition_variable>
#include<queue>
#include<thread>
#include<stack>
#include<stdio.h>
#include<vector>
#include<unordered_map>
#include<time.h>
#include<algorithm>
using namespace std;
typedef char ElemType;
typedef struct BtNode
{
	ElemType data;
	BtNode* leftchild;
	BtNode* rightchild;
	BtNode* parent;
}BtNode, * BinaryTree;









#if 0
int find(vector <int>& a)
{
	while (1)
	{
		srand(time(NULL));
		int index = rand() % a.size();
		int cnt = 0;
		int ma = a[index];
		for (int i = 0; i < a.size(); ++i)
		{
			if (a[i] == ma)
			{
				cnt += 1;
			}
		}
		if (cnt > a.size() / 2)
		{
			return ma;
		}
	}
}

int main()
{
	vector<int> a = { 2,3,3,3,3,3,3,3,6,7,8,8,9 };
	cout << find(a) << endl;
}
int find(vector<int>& a)
{
	sort(a.begin(), a.end());
	return a[a.size() / 2];
}

int find(vector<int>& a)
{
	int cot = 0;
	int m = a.front();
	for (int i = 0; i < a.size(); ++i)
	{
		if (m == a[i])
		{
			cot++;
		}
		else
		{
			cot--;
		}
		if (cot == 0)
		{
			m = a[i + 1];
		}
	}
	return m;
}


int find(vector<int>& a)
{
	unordered_map<int, int> counts;
	int ma = 0, cnt = 0;
	for (auto x : a)
	{
		++counts[x];
	}
	int n = a.size() / 2;
	for (auto x : counts)
	{
		if (x.second > n)
		{
			return x.first;
		}
	}
	return -1;
}







int Find(vector<int>& a, int val)
{
	int pos = -1;
	int left = 0;
	int right = a.size() - 1;
	while (left <= right)
	{
		int mid = left + (right - left) / 2;
		if (val <= a[mid])
		{
			right = mid - 1;
		}
		else if (val > a[mid])
		{
			left = mid + 1;
		}
		else
		{
			while (mid > 0 && a[mid - 1] == val)
			{
				--mid;
			}
			break;
		}
	}
	return pos;
}


int main()
{
	vector<int> a = { 1,2,3,4,5,6,7,8 };
	Find(a, 10);

}






typedef struct ListNode
{
	int data;
	struct ListNode* next;
}ListNode;
void Insert(ListNode* head, int value)
{
	ListNode* p = new ListNode();
	p->data = value;
	p->next = NULL;
	if (head == NULL)
	{
		head = p;
	}
	else
	{
		ListNode* node = head;
		while (node->next != NULL)
		{
			node = node->next;
		}
		node->next = p;
	}
}




mutex mtx;
condition_variable cv;
queue<int> q;
int dat = 0;
int maxsize = 10;
void Produce()
{
	while (true)
	{
		this_thread::sleep_for(chrono::microseconds(1000));
		unique_lock<mutex> lock(mtx);
		cv.wait(lock, []() {
			return q.size() < maxsize;
			});
		q.push(++dat);
		cout << "p id" << this_thread::get_id() << "dat" << dat << " q.size" << q.size() << endl;
		cv.notify_all();
	}
	
}
void Consumer()
{
	while (true)
	{
		this_thread::sleep_for(chrono::microseconds(500));
		unique_lock<mutex> lock(mtx);
		cv.wait(lock, []()
			{
				return q.size() > 0;
			});
		int c_data = q.front();
		q.pop();
		cout << "c id" << this_thread::get_id() << "c_data " << c_data << " q.size " << q.size() << endl;
		cv.notify_all();
	}
}

int main()
{
	thread t1[3];
	thread t2[3];
	for (auto& t : t1)
	{
		t = thread(Consumer);
	}
	for (auto& t : t2)
	{
		t = thread(Produce);
	}
	for (auto& t : t1)
	{
		t.join();
	}
	for (auto& t : t2)
	{
		t.join();
	}
	return 0;
}





template<class T>
class Stack
{
public:
	Stack(int size);
	~Stack();
	bool Empty();
	bool IsFull();
	bool pop();
	bool Push(T value);
	void traverse();
	bool StackClear();
	int stackLengh();
private:
	T value;
	T* base;
	T top;
	int maxsize;
};
template<class T>
Stack<T>::Stack(int size)
{
	maxsize = size;
	base = new T[size];
	top = 0;
}
template<class T>
Stack<T>::~Stack()
{
	delete[] base;
	base = NULL;
}
template<class T>
bool Stack<T>::IsFull()
{
	return top = maxsize;
}

template<class T>
bool Stack<T>::Empty()
{
	if (top = base)
	{
		return true;
	}
	return false;
}




int main()
{
	stack<int> s;
	int sum = 0;
	for (int i = 0; i <= 10; ++i)
	{
		s.push(i);
	}
	cout << "size is" << s.size() << endl;
	while (!s.empty())
	{
		cout << " " << s.top() << endl;
		s.pop();
	}
	cout << endl;
	return 0;
}




mutex mtx;
condition_variable cv;
int maxsize = 10;
int dat = 0;
queue<int> q;
void produce()
{
	while (1)
	{
		this_thread::sleep_for(chrono::microseconds(1000));
		unique_lock<mutex> lock(mtx);
		cv.wait(lock, []() {
			return q.size() < maxsize;
			});
		q.push(++dat);
		cout << "p   id" << this_thread::get_id() << " dat:" << dat <<"   q.size"<< q.size() << endl;
		cv.notify_all();
	}
}
void consume()
{
	while (1)
	{
		this_thread::sleep_for(chrono::microseconds(500));
		unique_lock<mutex> lock(mtx);
		cv.wait(lock, []() {
			return q.size() > 0;
			});
		int c_data = q.front();
		q.pop();
		cout << "c   id" << this_thread::get_id() << "c_data:" << c_data << "   q.size" << q.size() << endl;
		cv.notify_all();
	}
}
int main()
{
	thread t1[3];
	thread t2[3];
	for (auto& t : t1)
	{
		t = thread(consume);
	}
	for (auto& t : t2)
	{
		t = thread(produce);
	}
	for (auto& t : t1)
	{
		t.join();
	}
	for (auto& t : t2)
	{
		t.join();
	}
	return 0;
}





void fun()
{
	cout << " 线程" << endl;
}
int main()
{
	thread t1(fun);
	t1.detach();
	return 0;
}



class Queue
{
public:
	Queue() :qu() {}
	~Queue() {}
	void put(int val)
	{
		unique_lock<mutex> lock(mtx);
		qu.push_back(val);
	}
	int get()
	{
		unique_lock<mutex> lock(mtx);
		int val = qu.front(); qu.pop_front();
		return val;
	}
private:
	deque<int> qu;
	std::mutex mtx;
};
const int MaxElem = 5;

Queue qu;
std::counting_semaphore psm(MaxElem);
std::counting_semaphore csm(0);
std::mutex mtx;
const int n = 100;
int val = 0;
void Producer(int id)
{
	for (int i = 0; i < n; ++i)
	{
		psm.acquire(); // P 
		//mtx.lock();
		this_thread::sleep_for(std::chrono::milliseconds(10));
		cout << "Producer  id:  " << id << "Prod Elem: " << ++val << endl;
		//qu.push_back(val);
		qu.put(val);
		//mtx.unlock();
		csm.release(1);
	}
	cout << "Producer end" << endl;
}
void Consumer(int id)
{
	for (int i = 0; i < n; ++i)
	{
		csm.acquire();
		//mtx.lock();
		this_thread::sleep_for(std::chrono::milliseconds(200));
		//int x = qu.front();
		//qu.pop_front();
		int x = qu.get();
		cout << "Consumer: id " << id << " Cons Elem: " << &x << " " << x << endl;
		//mtx.unlock();
		psm.release(1);
	}
	cout << "Consumer end" << endl;
}

int main()
{
	std::thread prod1(Producer, 1);
	std::thread prod2(Producer, 2);

	std::thread cons1(Consumer, 1);
	std::thread cons2(Consumer, 2);

	prod1.join();
	prod2.join();
	cons1.join();
	cons2.join();
	return 0;
}




#endif // 0


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多个生产者消费者问题可以使用多线程和同步机制来实现。 下面是一个使用C++11中的线程库和互斥锁(mutex)和条件变量(condition_variable)来解决多个生产者消费者问题的示代码: ```c++ #include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;queue&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; using namespace std; // 生产者消费者问题中的缓冲区 queue&lt;int&gt; buffer; // 互斥锁和条件变量 mutex mtx; condition_variable cv; // 生产者线程函数 void producer(int id) { for (int i = 0; i &lt; 10; ++i) { // 生产一个任务 int task = i + id * 10; { // 加锁 unique_lock&lt;mutex&gt; lock(mtx); // 如果缓冲区已满,等待 while (buffer.size() == 10) { cv.wait(lock); } // 将任务放入缓冲区 buffer.push(task); cout &lt;&lt; &quot;Producer &quot; &lt;&lt; id &lt;&lt; &quot; produces task &quot; &lt;&lt; task &lt;&lt; endl; // 通知等待的消费者线程 cv.notify_all(); } } } // 消费者线程函数 void consumer(int id) { while (true) { { // 加锁 unique_lock&lt;mutex&gt; lock(mtx); // 如果缓冲区为空,等待 while (buffer.empty()) { cv.wait(lock); } // 从缓冲区取出一个任务 int task = buffer.front(); buffer.pop(); cout &lt;&lt; &quot;Consumer &quot; &lt;&lt; id &lt;&lt; &quot; consumes task &quot; &lt;&lt; task &lt;&lt; endl; // 通知等待的生产者线程 cv.notify_all(); } // 模拟消费任务的过程 this_thread::sleep_for(chrono::milliseconds(100)); } } int main() { // 创建两个生产者线程和三个消费者线程 vector&lt;thread&gt; producers, consumers; for (int i = 0; i &lt; 2; ++i) { producers.emplace_back(producer, i); } for (int i = 0; i &lt; 3; ++i) { consumers.emplace_back(consumer, i); } // 等待所有线程结束 for (auto&amp; t : producers) { t.join(); } for (auto&amp; t : consumers) { t.join(); } return 0; } ``` 在上面的示代码中,生产者线程每次生产一个任务并将其放入缓冲区,消费者线程每次从缓冲区取出一个任务并消费。如果缓冲区已满,生产者线程会等待,直到缓冲区有空闲位置;如果缓冲区为空,消费者线程会等待,直到缓冲区有任务。在等待时,线程会释放互斥锁,直到条件变量通知它继续执行。同时,生产者线程在将任务放入缓冲区后会通知等待的消费者线程,消费者线程在消费任务后会通知等待的生产者线程。这样就可以保证生产者消费者的同步和互斥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值