线程同步的几个问题

#include
#include
#include

using namespace std;

void handle1(int time)
{
	std::this_thread::sleep_for(std::chrono::seconds(time));
	cout << "hello thread1" << endl;
}
void handle2(int time)
{
	std::this_thread::sleep_for(std::chrono::seconds(time));
	cout << "hello thread2" << endl;
}

//namespace jack {
//	class semaphore {
//	public:
//		semaphore(int value = 1) :count(value), wakeups(0) {}
//		void wait() {
//			std::unique_lock lock(mutex);
//			if (--count < 0) {
//				condition.wait(lock, [&]()->bool {return wakeups > 0;});
//				--wakeups;
//			}
//		}
//		void post() {
//			std::lock_guard lock(mutex);
//			if (++count <= 0)
//			{
//				++wakeups;
//				condition.notify_one();
//			}
//		}
//	private:
//		int count;
//		int wakeups;
//		std::mutex mutex;
//		std::condition_variable condition;
//	};
//}
namespace jack
{
	class semaphore {
	public:
		semaphore(int val = 1) :count(val), wakeups(0) {}
		void wait()
		{
			unique_lock lock(mtx);
			if (--count < 0)
			{
				con.wait(lock, [&]()->bool {return wakeups > 0; });
				--wakeups;
			}
		}
		void post()
		{
			unique_lock lock(mtx);
			if (++count >= 0)
			{
				++wakeups;
				con.notify_one();
			}
		}
	private:
		int count;
		int wakeups;
		mutex mtx;
		condition_variable con;
	};
}
jack::semaphore sem(1);
jack::semaphore sA(1);
jack::semaphore sB(0);
void PrintA(int i)
{
	while (true)
	{
		sA.wait();
		sem.wait();
		cout << "A" << endl;
		this_thread::sleep_for(chrono::milliseconds(100));
		sem.post();
		sB.post();
	}
}
void PrintB(int i)
{
	while (true)
	{
		sB.wait();
		sem.wait();
		cout << "B" << endl;
		this_thread::sleep_for(chrono::milliseconds(100));
		sem.post();
		sA.post();
	}
}
int main()
{
	thread t1(PrintA, 1);
	thread t2(PrintB, 1);
	t1.join();
	t2.join();
}
//卖票问题
#if 0
int ticket = 100;
mutex mtx;
void sell(int i)
{
	while (ticket > 0)
	{
		lock_guard guard(mtx);
		if (ticket > 0)
		{
			cout << i << "窗口卖出" << ticket-- << endl;
		}
		this_thread::sleep_for(chrono::milliseconds(100));
	}
}
int main()
{
	thread t1(sell, 1);
	thread t2(sell, 2);
	thread t3(sell, 3);

	t1.join();
	t2.join();
	t3.join();

	cout << "卖完了" << endl;
}
#endif

 

你可能感兴趣的:(C++)