thread 当中的锁

一个简单的linux中的thread程序

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

#include <sys/time.h>

#include <unistd.h>

#include <pthread.h>

#include "t_util.h"

 

using namespace std;

 

int static volatile globalNumber = 0;

pthread_mutex_t static lock;

 

void *mythread(void *arg){

int aa = 0;

for(int i=0;i<5000;i++){

Pthread_mutex_lock(&lock);

globalNumber++;

Pthread_mutex_unlock(&lock);

aa+=1;

}

// cout<< aa<<endl;

 

*(int *)arg = aa;

 

// cout << (char *)arg <<endl;

return NULL;

}

 

int main(int argc, char *argv[]){

pthread_t p1,p2;

 

int rc;

pthread_mutex_init(&lock,NULL);

 

cout <<"main: begin" <<endl;

int a,b;

 

rc = pthread_create(&p1,NULL,mythread,(void *)&a);

rc = pthread_create(&p2,NULL,mythread,(void *)&b);

 

rc=pthread_join(p1,NULL);

rc=pthread_join(p2,NULL);

cout<<"b:"<<b<<endl;

cout <<"main: end"<<endl;

cout<<"a:"<<a<<endl;

cout<<globalNumber<<endl;

return 0;

}

 

接着说一下锁,锁基本有三个要求:1,正确的互斥;2,保证后一个人抢锁的公平性;3,性能

 

Test-and-set,compare-and-swap,Load-Linked and Store-Conditional(有点像redis实现的分布式锁)

1 int LoadLinked(int *ptr) {
2 return *ptr;
3 }
4
5 int StoreConditional(int *ptr, int value) {
6 if (no one has updated *ptr since the LoadLinked to this address) {
7 *ptr = value;
8 return 1; // success!
9 } else {
10 return 0; // failed to update
11 }
12 }

这三种都没有能解决第二个问题,公平性

 

Fetch-And-Add就类似于每个人排队等一张票,等到就能在接下去执行,但是仍是一个spin-wait型的锁。性能差

 

单纯yield在线程多的时候还是有需要yield太多的问题。使用一个queue可以解决:靠竞争一个guard来获得操作的机会,在操作中只有一个人可以置flag,flag置了就占到了锁,然后后面的没抢到锁的人都进队列,然后从队列里出来挨个运行。(仍然有wakeup/waiting race的问题)

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值