首页 > 解决方案 > 不同类型的输出 XCode 与 G++?

问题描述

以下代码在 XCode 中编译。但我想在没有编译器优化的情况下运行它,所以尝试使用g++ -std=c++14 falsesharing.cpp.

好吧,我得到了两种不同的输出。XCode 的整数和 G++ 的随机字符。有人知道这是为什么吗?

只是为了确定:G ++没有编译器优化吗?但是 XCode 可以吗?

#include <iostream>
#include <thread>
#include <vector>
#include <stdio.h>
#include <memory>
#include "timer.h"
using namespace std;

const int64_t g_numLoops = 1<<27;

void f(uint8_t *pBuffer, int offset){
    for(int64_t i=0; i<g_numLoops; i++){
        pBuffer[offset] +=1;
    }
}

int main(int argc, const char * argv[]) {
    cout << "Start! \n";
    vector<thread> multipleThreads(4);
    uint8_t buffer[256];
    int multiplier[] = {1,2,4,8,16,32,64,128,256};
    unique_ptr<Timer[]> timers = make_unique<Timer[]>(256);

    for(int i=0; i<multipleThreads.size(); i++){
        int offset = multiplier[i] * i;
        
        multipleThreads[i] = thread(f, buffer, offset);
    }
    for(auto &t: multipleThreads){
        t.join();
    }

    int counter = 0;
    for(auto i: buffer){
        cout << "Buffer "<< counter << " : " << i << endl;
    }
    
    cout << "Stop! \n";
    return 0;
}

标签: c++multithreadingconcurrency

解决方案


推荐阅读