【问题标题】:Multi-threaded Coin-toss Experiment [closed]多线程抛硬币实验[关闭]
【发布时间】:2016-05-05 18:08:34
【问题描述】:

前面的要点:我需要做些什么更改才能在我的记录中显示正确的正面/反面值?

编辑 1:一旦线程超过 1 个,Record 中的整数数组似乎会填充随机值。

我这几天一直在尝试调试它。我的代码是完整的并且可以完全执行。 (大家都知道,我是学生,不假装是专业程序员。)

在我的多线程抛硬币程序中,我试图捕捉每个线程中出现正面或反面的次数。我一共掷硬币一亿次。 (一亿。)

我的记录类中的数组元素没有正确累积。我知道我不需要使用互斥锁,因为每个线程都在访问线程唯一的单独内存位置。但是线程错误地更新了值,这不应该发生。

以下是我的调试示例。

  1. 单线程(注意头/尾的正确数量):

  1. 两个线程(现在头/尾计数简直疯了。):

下面是完全可执行的代码示例,然后是示例输出。另外,here 也是 Github 上完整代码的链接:

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <random>
#include <algorithm>
#include <time.h>
#include <strstream>
#include <random>


using namespace std;

default_random_engine dre;
uniform_int_distribution<int> Tosser(0,1);

struct Record {
    Record();
    ~Record();
    int numThreads;
    int *heads;
    int *tails;
    time_t startTime;
    time_t stopTime;
    time_t duration;
    int timesToToss;
};

Record::Record(): numThreads(0), heads(NULL), tails(NULL), startTime(NULL), stopTime(NULL), timesToToss(0){}
Record::~Record() {
    startTime = NULL;
    stopTime = NULL;
    duration = NULL;
    timesToToss = NULL;
    delete [] heads;
    heads = NULL;
    delete [] tails;
    tails = NULL;
    numThreads = NULL;
}

void concurrency(){
    vector<thread> threads;

    Record *records = new Record[4];
    Record *recPtr;
    int *numThrPtr;
    int *headsPtr;
    int *tailsPtr;
    time_t *startTimePtr;
    time_t *stopTimePtr;

    vector<time_t> durations;

    int timesToToss = 100000000; // Times to flip the coin.
    int index = 0; // Controls which record is being accessed.

    for(int i=1;i<3;i*=2){ //Performs 2 loops. 'i' is calculated to represent the number of threads for each test: 1, and 2 (full code contains up to 8 threads.)

        recPtr = &records[index]; //Get the address of the next record in the Record array.
        recPtr->timesToToss = timesToToss; //
        recPtr->numThreads = i; //Record the quantity of threads.
        recPtr->heads = new int[recPtr->numThreads]; //Create a new heads array, of 'x' elements, determined by number of threads.
        recPtr->tails = new int[recPtr->numThreads]; //Create a new tails array, of 'x' elements, determined by number of threads.
        recPtr->startTime = time(0); //Record the start time.

        for(int j = 0;j<recPtr->numThreads;j++){ //Start multi-threading.

            headsPtr = &recPtr->heads[j]; // Get the address of the index of the array, one element for each thread for heads.
            tailsPtr = &recPtr->tails[j]; // Get the address of the index of the array, one element for each thread for heads.

            threads.push_back(thread([&headsPtr, &tailsPtr, timesToToss](){for(int k=0;k<timesToToss;k++){ if (Tosser(dre)) ++(*headsPtr); else ++(*tailsPtr); } })); //Toss a coin!
        }

        for(auto& thread: threads) thread.join(); // Collect/join all the threads.

        while(!threads.empty()){ //Don't want to try and join 'live' threads with 'dead' ones!
            threads.pop_back();//Clear out the threads array to start with an empty array the next iteration.
        }

        recPtr->stopTime = time(0); //Record the end time.

        recPtr->duration = recPtr->stopTime - recPtr->startTime;

        timesToToss /= 2; //Recalculate timesToToss.
        ++index; //Increase the index.
    }

    for (int i=0;i<4;i++){ //Display the records.
        recPtr = &records[i];
        cout << "\nRecord #" << i+1 << ", " << recPtr->numThreads << " threads.";
        cout << "\nStart time: " << recPtr->startTime;
        cout << "\nStop time: " << recPtr->stopTime;
        cout << "\nTossed " << recPtr->timesToToss << " times (each thread).";
        cout << "\nHeads appeared << " << recPtr->heads << " times.";
        cout << "\nTails appeared << " << recPtr->tails << " times.";
        cout << "\nIt took " << recPtr->duration << " seconds.";
        durations.push_back(recPtr->duration);
        cout << "\n" << endl;
    }

    sort(durations.begin(),durations.end());

    cout << "Shortest duration: " << durations[0] << " seconds." << endl;

    delete [] records;
    records = NULL;
}

int main() {

    concurrency();

    return 0;
}

记录 #2 的输出是[更新于 2016 年 5 月 5 日 @ 下午 2:16 CST]:

Record #2, 2 threads.
Start time: 1462472702
Stop time: 1462472709
Tossed 50000000 times (each thread).
Heads appeared << 474443746 times.
Tails appeared << -1829315114 times.
It took 7 seconds.

Shortest duration: 3 seconds.

Process finished with exit code 0

【问题讨论】:

  • int *heads; 是一个指针,所以&lt;&lt; 将打印它的地址。如果您打算将此作为计数,为什么这是一个指针?
  • 好的。我现在看到了。每个线程都有自己的计数器。您需要对每个线程的计数器求和并打印总和。
  • 删除了我的答案,因为将其全部整理出来需要的时间比我目前所能承受的要多。
  • @LightnessRacesinOrbit 我的代码专门用于测试 1、2、4 和 8 个线程。这需要多个语句才能完成。我敢肯定,如果人们不能复制/粘贴和运行,那将是不完整的。它是最小的。我只有一个问题:“我需要做些什么更改才能在我的记录中显示正确的正面/反面值?”我的例子是完整的,可验证的。你也没有用。
  • @LightnessRacesinOrbit 最小!= 小。这意味着最少需要。我对使其完整和可验证的要求最少,因此最少。抱歉花了你这么长时间才读完。再见。

标签: c++ multithreading pointers dereference dynamic-allocation


【解决方案1】:

int *heads;heads 定义为指针。

&lt;&lt; 的默认行为是打印指针的地址,而不是指向的数据。指向char 的指针打印出 c 样式字符串时存在例外情况。

由于每个线程都有自己的int 来计算线程生成的磁头数,因此当线程完成后,磁头数必须相加并打印出来。

另外,

recPtr->heads = new int[recPtr->numThreads]; 

为头计数器分配了存储空间,但我在代码中找不到任何东西来初始化它们。这是未定义的行为。一个简单的 hack 解决方法是:

    for(int j = 0;j<recPtr->numThreads;j++){

        recPtr->heads[j] = 0;
        recPtr->tails[j] = 0;
        headsPtr = &recPtr->heads[j]; // Get the address of the index of the array, one element for each thread for heads.
        tailsPtr = &recPtr->tails[j]; // Get the address of the index of the array, one element for each thread for heads.

        threads.push_back(thread([&headsPtr, &tailsPtr, timesToToss]()
        {
            for(int k=0;k<timesToToss;k++)
            { 
                if (Tosser(dre)) ++(*headsPtr); 
                else ++(*tailsPtr); 
            } 
        })); //Toss a coin!
    }

最后,(编辑 3)lambda 定义thread([&amp;headsPtr, &amp;tailsPtr, timesToToss]() 捕获指向headsPtrtailsPtr 的指针,所以当线程有机会启动时,所有线程都指向headsPtr 和@987654332 @ 最后一个线程。

Hack kludge 现在是:

    for (int j = 0; j < recPtr->numThreads; j++)
    {

        recPtr->heads[j] = 0;
        recPtr->tails[j] = 0;
        headsPtr = &recPtr->heads[j]; // Get the address of the index of the array, one element for each thread for heads.
        tailsPtr = &recPtr->tails[j]; // Get the address of the index of the array, one element for each thread for heads.

        threads.push_back(thread([headsPtr, tailsPtr, timesToToss]()
        {
            for(int k=0;k<timesToToss;k++)
            {   
                if (Tosser(dre)) ++(*headsPtr);
                else ++(*tailsPtr);
            }
        })); //Toss a coin!
    }

我已经清理了 lambda 的格式,以使出错的地方更易于阅读。

【讨论】:

  • 你是一位才华横溢、才华横溢的程序员!感谢您的帮助!
猜你喜欢
  • 2018-07-08
  • 2016-03-28
  • 2016-09-13
  • 2014-05-25
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多