thread, c++11, dziwny blad, wielowatkowosc

0
#include <iostream>
#include <thread>

class MyClass
{
public:
	MyClass(){}
	int tab[5];
	~MyClass(){}
};

void write(MyClass *temp)
{
	for (int i = 0; i < 5; ++i)
		temp->tab[i] = i + 90;
}

int main()
{
	std::thread td(write);
	MyClass *my_class = new MyClass();
	for (int i = 0; i < 5; ++i)
		my_class->tab[i] = i;

	for (int i = 0; i < 5; ++i)
		printf_s(my_class->tab[i] + " ");
	return 0;
} 

Dlaczego ten kod mi się nie kompiluje i wywala:

Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)' threading c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread 238

Tak wiem, że doprowadzam w kodzie do szkodliwej rywalizacji, ale chciałbym dokładnie się dowiedzieć dlaczego taki błąd akurat.

2

Jaki jest parametr przekazany do write? Gdzie jest on przekazany? Jak?

0
#include <iostream>
#include <thread>

class MyClass
{
public:
	MyClass(){}
	int tab[5];
	~MyClass(){}
};

void write(MyClass *temp)
{
	for (int i = 0; i < 5; ++i)
		temp->tab[i] = i + 90;
}

int main()
{
	MyClass *my_class = new MyClass();
	std::thread td(write,my_class);
	for (int i = 0; i < 5; ++i)
		my_class->tab[i] = i;

	for (int i = 0; i < 5; ++i)
		printf_s(my_class->tab[i] + " ");
	return 0;
} 

Aaa faktycznie. Ale teraz mam okienko dialogowe Debug Error. Abort() has been called.

0

To co robisz jest głupie.
Co próbujesz osiągnąć?

//EDIT:
Jeżeli chcesz uczyć się wielowątkowości, to z miejsca zainteresuj się std::async i std::future; Przykład:

#include <thread>
#include <future>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

namespace data {
    using cont = std::vector<int>;
    using future = std::future<cont>;
    using futures = std::vector<future>;
}

template<typename Func>
auto heavy_operation(Func func, size_t times = 1'000'000) {
    data::cont result;
    result.reserve(times);
    while(times --> 0) {
        result.push_back(func(times));
    }
    return result;
}


using namespace std;
int main() {
    data::futures futures;
    
    for(size_t i = 1; i <= 10; ++i) {
        futures.push_back(
            async([=]{
                return heavy_operation([=](int x) {
                    return x % (i*i);
                });
            })
        );
    }
    
    for(auto &future: futures) {
        auto cont = future.get();
        cout << "size: " << cont.size()
             << ", first 10 elements: \n";
        
        copy(begin(cont), 
             begin(cont)+10, 
             ostream_iterator<int>(cout, " "));
        cout << "\n";
    }
    
    return 0;
}

http://melpon.org/wandbox/permlink/uUSGo6mOXGbVwcY9

1 użytkowników online, w tym zalogowanych: 0, gości: 1