Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

Ubuntu多线程下测试++运算符

#include <stdio.h>
#include <unistd.h>
#include <thread>
using namespace std;
const int threadNum = 1000;
int test = 5;
void add(){
    test++;
}
int main(){
    
    thread thread_id[threadNum];

    for(int i=0;i<threadNum;i++){
        thread_id[i] = thread(add);
    }
    for(int i=0;i<threadNum;i++){
        thread_id[i].join();
    }
    printf("%d
",test);
    return 0;
}

运行了很多遍,结果都是1005呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

太快了,搞多点

void add() {
    for (int i = 0; i < 1000; i++)
        test++;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...