几个用于线程同步的锁

本文介绍了三种提高多线程程序性能的锁机制:可重入锁、自旋锁和读写锁。可重入锁允许同一线程多次获取锁而不致死锁;自旋锁通过循环尝试获取锁的方式减少上下文切换;读写锁允许多个线程同时读取共享资源,但写操作具有排他性。
摘要由CSDN通过智能技术生成

It's well known that synchronous processing is necessary for multithreaded programming. The operating system provides some basic way, such as critical section, mutex. However, those methods are not enough for large systems. I present three locks that can provide higher performance.

 

Recursive lock

It can be acquired repeatedly by the thread holding the lock. And that will not result in deadlock. There must be a unlock operation corresponding to each lock operation in the thread holding the lock so that the other thread can acquire it. It's useful in the scenario that a thread may acquire a lock many times, especially in the recursive functions. However, it's slower than non-recursive lock.

 

Spin lock

The waiting thread doesn't block at the synchronizing point, but "spins" to try to acquire the lock. Spinlocks do have a advantage in that no context switch is required when a thread must wait on a lock, and a context switch may take considerable time. Thus, when locks are expected to be held for short times, spinlocks are useful. They are often employed on multiprocessor systems where one thread can "spin" on one processor while another thread run on another processor. Note that misuse of it may reulst in thread starvation. It can be solved by queuing the waiting threads.

 

Read and write lock

It is also called as multiple read/single-write lock. It permit multiple thread to read the shared resources concurrently, while only one thread can be authorised to perform write operation at most. It's a high performance mechanism for those applications which multiple threads may often read the shared resources at the same time and the write operation is performed less times. Well for long shared data, it's desirable to divide it into more segments to use read-write lock for synchronizing.

 

The code is shown as follow:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值