int自增操作到底是不是原子性?验证了下答案是否定的,当多线程遇到简单的自增操作时会出现问题,比如开启很多个线程同时对一个int自增后结果会随着系统负载出现不同的结果。
代码验证:
#include<unistd.h>
#include<pthread.h>
#include<iostream>
using namespace std;
static int i=0;
class test{
public:
test():a(0),b(0.0){}
void increase(){//对变量自增
a++;
b++;
}
void get() const{
cout<<"a="<<a<<" b="<<b<<endl;
}
private:
int a;
double b;
};
void* worker(void* arg){
sleep(100-i++);//每个线程睡眠一定时间以期达到这些线程能同时对变量进行操作,当然这里本身就不是线程安全的,因为结果得到:自增不是线程安全的
test* temp=(test*)arg;
temp->increase();
}
int main(){
pthread_t pthd[100];
test* one=new test;
for(int i=0;i<100;i++){
pthread_create(&pthd[i],NULL,worker,one);//开启100个线程对变量自增
}