最普通的互斥锁,谁竞争到改锁,谁访问临界资源
std::mutex mtx;
int shared_data = 0;
void add() {
mtx.lock();
shared_data++;
mtx.unlock();
}
int main() {
std::thread t1(add);
std::thread t2(add);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
递归锁,普通的锁是不能递归的,一个线程加锁后,再递归,会导致死锁
std::recursive_mutex rmtx;
int shared_data = 0;
void add(int depth) {
std::cout << std::this_thread::get_id() << std::endl;
if (depth <= 0) {
return;
}
rmtx.lock();
++shared_data;
add(depth-1);
rmtx.unlock();
}
int main() {
std::thread t1(add, 5);
std::thread t2(add, 5);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
尝试加锁有时间限制,若超过了这个时间,就自动释放锁,并返回加锁失败
std::timed_mutex tmtx;
int shared_data = 0;
void add() {
if (tmtx.try_lock_for(std::chrono::seconds(2))) {
++shared_data;
std::this_thread::sleep_for(std::chrono::seconds (1));
tmtx.unlock();
} else {
std::cout << "Timeout, could not lock mutex." << std::endl;
}
}
int main() {
std::thread t1(add);
std::thread t2(add);
t1.join();
t2.join();
std::cout << "shared_data: " << shared_data << std::endl;
return 0;
}
读写锁,可以允许多个读者读,但是写的时候,只允许有一个写者;注意读者加锁用的 shared_lock
std::shared_mutex smtx;
int shared_data = 0;
void read_data() {
std::shared_lock<std::shared_mutex> lock(smtx);
std::cout << "Read data: " << shared_data << std::endl;
}
void write_data(int value) {
std::unique_lock<std::shared_mutex> lock(smtx);
shared_data = value;
std::cout << "Write data: " << shared_data << std::endl;
}
int main() {
std::vector<std::thread> readers;
for (int i = 0; i < 5; ++i) {
readers.push_back(std::thread(read_data));
}
std::thread writer(write_data, 42);
for (auto& t : readers) {
t.join();
}
writer.join();
return 0;
}
man 3 pthread_rwlock_init
pthread_rwlock_init(pthread_rwlock_t* restrict rwlock,const pthread_rwlockattr_t* restrict attr );
pthread_rwlock_destroy(pthread_rwlock_t* rwlock);
pthread_rwlock_rdlock(pthread_rwlock_t* rdlock);
pthread_rwlock_wrlock(pthread_rwlock_t* rwlock);
#include
#include
#include
int number=0;
pthread_rwlock_t rwlock;
void *write_pthread(void * arg)
{
while(1)
{ //加写锁
pthread_rwlock_wrlock(&rwlock);
number++;
printf("write_pthread id:%ld, number is %d\n",pthread_self(),number);
pthread_rwlock_unlock(&rwlock);
//解锁
sleep(1);
}
}
void *read_pthread(void * arg)
{
while(1)
{ //加读锁
pthread_rwlock_wrlock(&rwlock);
printf("read_pthread id: %ld,number is %d\n",pthread_self(),number);
pthread_rwlock_unlock(&rwlock);
//解锁
sleep(1);
}
}
int main()
{
pthread_t p[8];
pthread_rwlock_init(&rwlock,NULL);
for(int i=0;i<3;i++)
{
pthread_create(&p[i],NULL,write_pthread,NULL);
}
for(int i=3;i<8;i++)
{
pthread_create(&p[i],NULL,read_pthread,NULL);
}
for(int j=0;j<8;j++)
{
pthread_join(p[j],NULL);
}
return 0;
}