C++11实现信号量semaphore

C++11实现信号量semaphore

描述

1)信号量是一种线程/进程间同步的一种手段,可以用来管理有限资源的访问;
2)互斥锁主要用来进行互斥的,而信号量则是主要用来同步的;
3)从使用上来说,互斥锁的lock和unlock必须在同一个线程;而信号量的wait和signal可以在不同的线程;
典型的线程同步代码如下所示:

#include"semaphore.h"
#include<thread>
#include<iostream>

semaphore sem(0);

void func1() {
	// do something
	std::this_thread::sleep_for(std::chrono::seconds(2));
	std::cout << "func1" << std::endl;
	sem.signal();
}

void func2() {
	sem.wait();
	//do something
	std::cout << "func2" << std::endl;
}

int main() {
	std::thread thread1(func1);
	std::thread thread2(func2);
	if (thread1.joinable())
		thread1.join();
	if (thread2.joinable())
		thread2.join();
}


源码

semaphore.h

#pragma once
#include<mutex>
#include<condition_variable>
class semaphore {
public:
	semaphore(long count = 0) :count(count) {}
	void wait() {
		std::unique_lock<std::mutex>lock(mx);
		cond.wait(lock, [&]() {return count > 0; });
		--count;
	}
	void signal() {
		std::unique_lock<std::mutex>lock(mx);
		++count;
		cond.notify_one();
	}

private:
	std::mutex mx;
	std::condition_variable cond;
	long count;
};



下面是一个使用Semaphore实现两线程同步的C++代码: ```c++ #include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <semaphore.h> using namespace std; sem_t sem; void thread1() { cout << "Thread 1 is running." << endl; sem_post(&sem); // 发送信号量 } void thread2() { sem_wait(&sem); // 等待信号量 cout << "Thread 2 is running." << endl; } int main() { sem_init(&sem, 0, 0); // 初始化信号量 thread t1(thread1); thread t2(thread2); t1.join(); t2.join(); sem_destroy(&sem); // 销毁信号量 return 0; } ``` 这个例子中,我们使用了`sem_t`和`sem_init()`、`sem_wait()`、`sem_post()`、`sem_destroy()`四个函数来实现Semaphore。`sem_t`是一个结构体类型,用于存储Semaphore的信息。`sem_init()`函数用于初始化Semaphore,第一个参数是Semaphore结构体指针,第二个参数是0表示这个Semaphore是用于线程间同步的,第三个参数是Semaphore的初值,这里设为0。`sem_wait()`函数用于等待Semaphore的信号,如果Semaphore的值为0,则该函数阻塞线程,直到Semaphore的值大于0;如果Semaphore的值大于0,则该函数将Semaphore的值减1,然后线程继续执行。`sem_post()`函数用于发送Semaphore的信号,将Semaphore的值加1,表示Semaphore可以被下一个等待的线程使用。`sem_destroy()`函数用于销毁Semaphore。 在这个例子中,我们创建了两个线程,线程1通过调用`sem_post()`函数发送Semaphore的信号,线程2通过调用`sem_wait()`函数等待Semaphore的信号。由于Semaphore的初值为0,线程2会在等待Semaphore的信号时被阻塞,直到线程1发送了Semaphore的信号。这样就实现了两个线程的同步。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值