0

При передачи строки получаю ошибку "error C2672: "std::invoke" ". Подскажите как правильно передать стрингу в потоку?

#include <iostream>
#include <thread>
#include <atomic>
#include <fstream>
#include <string>

std::atomic_bool f = true;
std::atomic_int number_thread = 0;
int n{0};


void func_1(int n, std::string & mess)
{
    while (mess[n] != *mess.end())
    {
        if (f == false)
        {
            break;
        }
        if (number_thread == n)
        {
            std::cout << mess[n++]  << " " << number_thread << std::endl;
            number_thread++;
            if (number_thread == 4)
            {
                number_thread = 0;
            }
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }
    }   
}

int main()
{
    int count_thread = std::thread::hardware_concurrency();
    std::cout << count_thread << std::endl;

    std::ifstream f1("test.obj");
    std::string mes{};
    f1 >> mes;
    for (int i = 0; i < 4; i++)
    {
        std::thread thr(func_1, i, mes);

        thr.detach();
    }   
    std::this_thread::sleep_for(std::chrono::seconds(5));
    f = false;  
    system("pause");
    return 0;
}
2
  • 1
    Функция func_1 принимает 2-й аргумент (строку) по ссылке. А вы передаете в поток - по значению. Вероятно, правильнее исправить сигнатуру функции на void func_1(int n, std::string mess) или void func_1(int n, const std::string & mess).
    – Chorkov
    19 сен 2019 в 8:20
  • Возможный дубликат вопроса: Создание потока в функции C++
    – user206435
    19 сен 2019 в 8:29

1 ответ 1

0

В описании конструктора std::thread написано:

The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with std::ref or std::cref).

Пишите std::thread thr(func_1, i, std::ref(mes));

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.