【问题标题】:How can I create a variable number of threads?如何创建可变数量的线程?
【发布时间】:2020-03-11 18:07:38
【问题描述】:

我正在尝试创建一个对全局变量进行加减运算的程序。加减特征将由线程处理。如何连续加/减,直到全局变量达到某个阈值?

假设我有以下代码,


#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <numeric>
#include <cmath>
#include <sstream>
#include <thread>
#include <chrono>
#include <ctime>
#include <mutex>

int GetRandom(int max){
    //generate a pseudo-random number with time as the seed
    //time as seed will always return a different starting point
    srand(time(NULL));
    //mod max to ensure we return a number below max
    return rand() % max;
}

std::string GetTime(){
    auto nowTime = std::chrono::system_clock::now();
    std::time_t sleepTime =
            std::chrono::system_clock::to_time_t(nowTime);
    return std::ctime(&sleepTime);
}

double acctBalance = 10;

// Protects shared data from being accessed at the
// same time
std::mutex acctLock;

void Add(int id,
        double adding, int sleep){
    int rand = GetRandom(10);
    // The exception safe way to protect access
    // to code within its scope. The lock is released
    // after execution leaves this scope
    std::lock_guard<std::mutex> lock(acctLock);

    // Blocks access between lock and unlock
    // until execution completes
    // This isn't good to use however if an error
    // occurs between lock and unlock
    // acctLock.lock();

    std::this_thread::sleep_for(std::chrono::seconds(sleep));

    std::cout << id <<
            ": adding : " <<
            rand << " on " <<
            GetTime() << ": slept for " << sleep<<"seconds"<< "\n";


    if((acctBalance - rand) <= 20){
        acctBalance += rand;
        std::cout << "New Account Balance is $" <<
                acctBalance << "\n";
    } else {
        std::cout << "Not Enough Money in Account\n";
        std::cout << "Current Balance is $" <<
                acctBalance << "\n";
    }
    // acctLock.unlock();
}

void Subtract(int id, double subtract, int sleep){
    int rand = GetRandom(10);
        // The exception safe way to protect access
    // to code within its scope. The lock is released
    // after execution leaves this scope
    std::lock_guard<std::mutex> lock(acctLock);

    // Blocks access between lock and unlock
    // until execution completes
    // This isn't good to use however if an error
    // occurs between lock and unlock
    // acctLock.lock();

    std::this_thread::sleep_for(std::chrono::seconds(sleep));

    std::cout << id <<
            " tries to withdrawal $" <<
            rand << " on " <<
            GetTime() << ": slept for " << sleep<<"seconds"<<"\n";

    if((acctBalance - rand) <=20){
        acctBalance -= rand;
        std::cout << "New Account Balance is $" <<
                acctBalance << "\n";
    } else {
        std::cout << "Not Enough Money in Account\n";
        std::cout << "Current Balance is $" <<
                acctBalance << "\n";
    }
    // acctLock.unlock();
}

int main()
{

    // We will create a pool of threads that
    // will access a bank account in no particular
    // order
    std::thread threads[2];

    int rand = 3;
    int x = 10;
      threads[0] = std::thread(Add, 0, 15,rand);
      threads[1] = std::thread(Subtract, 1, 15,rand);

      for(int i = 0; i < 2; ++i){
          threads[i].join();
      }

    return 0;
}

我目前创建了 2 个线程,1 个用于加法,另一个用于减法。但是我的程序每次只会从全局变量中加减一次。 我想我应该创建一个动态的线程数组,直到 acctBalance 达到某个数字。我将如何实现这一目标?

【问题讨论】:

标签: c++ multithreading


【解决方案1】:

这里没有什么复杂的,只需创建一个向量并为其添加线程:

std::vector<std::thread> threads;
threads.reserve(count);
for (size_t i = 0; i < count; i++)
{
  threads.emplace_back(Add, 0, 15,rand);
}
for (auto& thread : threads)
{
  thread.join();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多