🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

C++ thread problem

Started by
3 comments, last by cowcow 6 years, 2 months ago

I'm trying to write a simple multithreaded, but I get the error "no overloaded function takes 4 arguments". Any ideas why? My code is:


	#include <winsock2.h>
#include <Ws2tcpip.h>
#include <windows.h>
#pragma comment(lib, "ws2_32")
	#include <atomic>
using std::atomic_bool;
	#include <vector>
using std::vector;
	#include <thread>
using std::thread;
	#include <mutex>
using std::mutex;
	#include <vector>
using std::vector;
	#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
using std::cout;
using std::endl;
using std::string;
using std::istringstream;
using std::ostringstream;
using std::ios;
	
void thread_func(atomic_bool &stop, vector<string> &vs, mutex &m)
{
    while (!stop)
    {
        m.lock();
        vs.push_back("test");
        m.unlock();
	        Sleep(1000);
    }
}
	int main(void)
{
    atomic_bool stop = false;
    mutex m;
    vector<string> vs;
	    thread thread_a(thread_func, stop, vs, m);
    thread_a.join();
	    while (!stop)
    {
        m.lock();
	        for (vector<string>::const_iterator ci = vs.begin(); ci != vs.end(); ci++)
            cout << *ci << endl;
	        vs.clear();
	        m.unlock();
    }
	    return 0;
}
	

 

Advertisement

You're not stating which line gives the error but a quick guess would say: try wrapping the arguments with std::ref like this.


thread thread_a(thread_func, std::ref(stop), std::ref(vs), std::ref(m));

Life's like a Hydra... cut off one problem just to have two more popping out.
Leader and Coder: Project Epsylon | Drag[en]gine Game Engine

The reason behind @RPTD 's answer is that std::thread copies (or moves) the arguments before calling the function.
std::ref (and std::cref) gets you a copyable wrapper around a reference, which is the blessed way of passing a reference for the args of std::thread, please see the Notes at cppreference.

Please note that join() on a thread is blocking until the thread completes, so your loop in main will never be reached as the thread in its current state never has a reason to return.

To make it is hell. To fail is divine.

Thanks for the help... ref() seems to have done the trick!

This topic is closed to new replies.

Advertisement