一个简单的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的问题)