线程同步

线程同步

输出ABBCCCABBCCC…
用锁做了半天,用信号量一下子做出来了,c++没有自带的信号量库好烦

#include 
#include 
#include 
#include 
#include 

using namespace std;

class Semaphore
{
public:
	explicit Semaphore(unsigned int count); //用无符号数表示信号量资源
	~Semaphore();
public:
	void wait();
	void signal();
private:
	int m_count; //计数器必须是有符号数
	std::mutex m_mutex;
	std::condition_variable m_condition_variable;
};

//Semaphore.cpp


Semaphore::Semaphore(unsigned int count) :m_count(count) {
}

Semaphore::~Semaphore() {
}

void Semaphore::wait() {
	std::unique_lock<std::mutex> unique_lock(m_mutex);
	--m_count;
	while (m_count < 0) {
		m_condition_variable.wait(unique_lock);
	}
}

void Semaphore::signal() {
	std::unique_lock<std::mutex> lg(m_mutex);
	if (++m_count < 1) {
		m_condition_variable.notify_one();
	}
}

Semaphore a(1);
Semaphore b(0);
Semaphore c(0);

void functionA() {
	int count = 0;
	while (true) {
		a.wait();
		cout << "A";
		count++;
		if (count == 1) {
			count = 0;
			b.signal();
			b.signal();
		}
	}
}


void functionB() {
	int count = 0;
	while (true) {
		b.wait();
		cout << "B";
		count++;
		if (count == 2) {
			count = 0;
			c.signal();
			c.signal();
			c.signal();
		}
	}
}


void functionC() {
	int count = 0;
	while (true) {
		c.wait();
		cout << "C";
		count++;
		if (count == 3) {
			count = 0;
			a.signal();
		}
	}
}



int main() {
	vector<thread> thread_vec;
	thread_vec.push_back(thread(bind(functionA)));
	thread_vec.push_back(thread(bind(functionB)));
	thread_vec.push_back(thread(bind(functionC)));
	for (auto& threa : thread_vec) {
		threa.join();
	}
}

你可能感兴趣的:(算法,多线程)