Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ thread problem

Started by cowcow Apr 15, 2018 at 5:56 PM 3 replies 4.3k views
Original Post
cowcow
cowcow

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;
}
	



RPTD
RPTD

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));
Zao
Zao

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.
cowcow
cowcow

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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.