线程互斥同步

多线程编程,因无法知道哪个线程在哪个时候对共享资源进行操作,因此如何保护共享资源变得复杂,通过以下技术,可解决线程间对资源的竞争:
1 互斥量Mutex
2 信号灯Semaphore
3 条件变量Conditions
——————/
为何需互斥量:
Item * p =get_node;
process_job(p);
free(p);
线程1执行完Item * p =get_node,改而运行线程2,线程2同样取出头节点进行处理,最后释放该节点;过段时间线程1重新运行,此时p所指向节点已被释放,导致无法预料后果
对该情况,线程可在取出头节点前等待互斥量,如此时有其他线程已占用互斥量,则阻塞,只有等到…
——————/
互斥量类型pthread_mutex_t,使用前要对其进行初始化
对于静态分配(全局或static)的互斥量, 可将其设置为默认mutex对象PTHREAD_MUTEX_INITIALIZER
Eg:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
等价于用pthread_mutex_init初始化且attr为NULL

对于动态分配的互斥量, 在申请内存(malloc)之后, 通过pthread_mutex_init初始化, 且在释放内存(free)前需调用pthread_mutex_destroy
Eg:struct _globals包含pthread_mutex_t db,在malloc与free _globals结构体后前需……

int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *attr)
int pthread_mutex_destroy(pthread_mutex_t *mutex)
——————/加锁解锁
int pthread_mutex_lock(pthread_mutex_t *mutex)
int pthread_mutex_trylock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t *mutex)
返回值: 成功返回0, 出错返回错误编号
trylock非阻塞模式, 如没锁定则锁定,如已锁定则直接返回EBUSY
——————/互斥量PK信号量
Mutex是把钥匙,一个人拿了进入房间,出来时交给队列第一个
Semaphore是可容纳N人的房间,如人不满就可进入,如人满了就要等待有人出来,当N=1称binary semaphore
Binary semaphore与Mutex差异:
mutex要由获得锁线程释放(谁获得谁释放),而semaphore可由其它线程释放
初始状态可能不一样,mutex初始值1,而semaphore初始值可能是0或者1
——————/
Mutex Is a key to a toilet. One person can have the key – occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.Officially:“Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object
only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section.”

Semaphore:
Is the number of free identical toilet keys. Example,say we have four toilets with identical locks and keys. The semaphore count - the count of keys – is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Officially: “A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore).”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值