将线程放入向量线程时出错

问题描述

我正在尝试将线程分配给一个线程向量,以便我可以同时使用多个倒数计时器。这是一段未完成的代码,但是我在放入线程时已经卡住了。我想将线程放入线程向量中,所以我所做的是创建了一个线程,然后我使用了push_back()函数把线程放进去。但后来我收到了一条错误消息。这是我的代码

#include <vector>
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;

class countdown
{
public:
    int hours,minutes,seconds,totalsec;
    void cdexec ()
    {
        totalsec += hours * 3600;
        totalsec += minutes * 60;
        for (int cd=totalsec;cd>=0;cd--)
            Sleep(1000);
        cout << '\a';
    }
};

int obj_resize = 1,obj_count = 0;
vector<countdown> obj;
vector<thread> th;
void read_time();

int main()
{
    read_time();
}

void read_time()
{
    obj.resize(obj_resize);
    cout << endl << "Please Enter The Hours You Want To Countdown: ";
    cin >> obj[obj_count].hours;
    cout << endl << "Please Enter The Minutes You Want To Countdown: ";
    cin >> obj[obj_count].minutes;
    cout << endl << "Please Enter The Seconds You Want To Countdown: ";
    cin >> obj[obj_count].seconds;
    thread th1 (obj[obj_count].cdexec());
    th.push_back(move(th1));
    obj_count++;
    obj_resize++;
}

这是我得到的错误

no instance of constructor "std::thread::thread" matches the argument list argument types are: (void)

我该怎么办?

解决方法

我使用了 lamda 函数并将对 obj[obj_count].cdexec() 的调用放入其中:

此外,将 std::chrono 用于 sleep。并确保线程已连接。

#include <vector>
#include <iostream>
#include <thread>
#include <cstdlib>
#include <chrono>
// #include <Windows.h>
using namespace std;

class countdown
{
public:
    int hours,minutes,seconds,totalsec;
    void cdexec ()
    {
        totalsec = seconds;
        totalsec += hours * 3600;
        totalsec += minutes * 60;
        std::this_thread::sleep_for(std::chrono::seconds(totalsec));
        cout << '\a';
    }
};

int obj_resize = 1,obj_count = 0;
vector<countdown> obj;
vector<thread> th;
void read_time();

int main()
{
    read_time();
}

void read_time()
{
    obj.resize(obj_resize);
    cout << endl << "Please Enter The Hours You Want To Countdown: ";
    cin >> obj[obj_count].hours;
    cout << endl << "Please Enter The Minutes You Want To Countdown: ";
    cin >> obj[obj_count].minutes;
    cout << endl << "Please Enter The Seconds You Want To Countdown: ";
    cin >> obj[obj_count].seconds;
    thread th1 ([&]() { obj[obj_count].cdexec(); });
    th.push_back(move(th1));
    
    for (auto& t : th)
        t.join();
    obj_count++;
    obj_resize++;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...