Jump to content
  • Advertisement
cowcow

C++ thread problem

Recommended Posts

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

 

Share this post


Link to post
Share on other sites
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));
Edited by RPTD

Share this post


Link to post
Share on other sites

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.

Edited by Zao

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!