Advanced Programming in UNIX Environment Episode 57
发布日期:2021-10-07 23:47:37 浏览次数:2 分类:技术文章

本文共 2694 字,大约阅读时间需要 8 分钟。

Spin Locks

A spin lock is like a mutex, except that instead of blocking a process by sleeping, the process is blocked by busy-waiting (spinning) until the lock can be acquired. A spin lock could be used in situations where locks are held for short periods of times and threads don’t want to incur the cost of being descheduled.

The interfaces for spin locks are similar to those for mutexes, making it relatively easy to replace one with the other. We can initialize a spin lock with the pthread_spin_init function. To deinitialize a spin lock, we can call the pthread_spin_destroy function.

#include 
int pthread_spin_init(pthread_spinlock_t *lock,int pshared);int pthread_spin_destroy(pthread_spinlock_t *lock);

To lock the spin lock, we can call either pthread_spin_lock, which will spin until the lock is acquired, or pthread_spin_trylock, which will return the EBUSY error if the lock can’t be acquired immediately. Note that pthread_spin_trylock doesn’t spin. Regardless of how it was locked, a spin lock can be unlocked by calling pthread_spin_unlock.

#include 
int pthread_spin_lock(pthread_spinlock_t *lock);int pthread_spin_trylock(pthread_spinlock_t *lock);int pthread_spin_unlock(pthread_spinlock_t *lock);

Barriers

Barriers are a synchronization mechanism that can be used to coordinate multiple threads working in parallel. A barrier allows each thread to wait until all cooperating threads have reached the same point, and then continue executing from there. We’ve already seen one form of barrier—the pthread_join function acts as a barrier to allow one thread to wait until another thread exits.

We can use the pthread_barrier_init function to initialize a barrier, and we can use the pthread_barrier_destroy function to deinitialize a barrier.

#include 
int pthread_barrier_init(pthread_barrier_t *restrict barrier, const pthread_barrierattr_t *restrict attr, unsigned int count);int pthread_barrier_destroy(pthread_barrier_t *barrier);

We use the pthread_barrier_wait function to indicate that a thread is done with its work and is ready to wait for all the other threads to catch up.

#include 
int pthread_barrier_wait(pthread_barrier_t *barrier);
#include "apue.h"#include 
#include
#include
#define NTHR 8#define NUMNUM 8000000L#define TNUM (NUMNUM/NTHR)long nums[NUMNUM];long snums[NUMNUM];pthread_barrier_t b;#ifdef SOLARIS#define heapsort qsort#elseextern int heapsort(void *,size_t, size_t,int (*)(const void *,const void *));#endifint complong(const void *arg1, const void *arg2){ long l1=*(long *)arg1; long l2=*(long *)arg2; if(l1==l2) return 0; else if(l1

Using a barrier

转载地址:https://blog.csdn.net/myfather103/article/details/79824288 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:XAMPP Tomcat升级
下一篇:Advanced Programming in UNIX Environment Episode 56

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年03月29日 10时36分45秒