vc++多线程程序
MultiThread program in VC++
我正在尝试做一个线程应用程序,在队列后无限打印一组数字。我得到这个错误:
C3867: 'Test::ThreadFunc':函数调用缺少参数列表;使用'&Test::ThreadFunc'创建一个指向成员的指针。我做错了什么?错误是什么?
#include "stdafx.h"
#include <chrono>
#include <mutex>
#include <thread>
#include <list>
class Test {
std::list<int> queue;
std::mutex m;
public:
void ThreadFunc()
{
// Loop is required, otherwise thread will exit
for (;;)
{
bool read = false;
int value;
{
std::lock_guard<std::mutex> lock(m);
if (queue.size())
{
value = queue.front();
read = true;
queue.pop_back();
}
}
if (read)
{
// send(header.data(), header.dataSize());
// send(proto.data(), proto.dataSize());
printf("Hello %dn", value);
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void TestFunc()
{
std::thread thread(ThreadFunc);
thread.detach();
int i = 0;
// Loops only as a test example
for (;;)
{
std::lock_guard<std::mutex> lock(m);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
queue.push_back(i++);
// Queue Message(header, payload);
}
}
};
int main()
{
Test test;
test.TestFunc();
}
您正在尝试传递指向类的成员函数的指针。当你这样做时,有一个参数被添加到函数中,这是一个指针,指向你调用函数的类的实例。在您的示例中,指向类的指针将是this
指针。
回答你的评论,为什么它不是隐式传递?你不是作为类的成员调用函数,你是通过指针传递成员函数。这是一种不同的、独特的情况,请参阅以下参考:在c++中将成员函数作为参数传递
另外,为了避免以后的一些麻烦,下一个问题是std::thread的构造函数按值接受参数,所以如果需要通过引用传递任何参数,请查看std::ref.
修复方法如下。这个作品。谢谢你@mock_blatt
#include "stdafx.h"
#include <chrono>
#include <mutex>
#include <thread>
#include <list>
class Test {
std::list<int> queue;
std::mutex m;
public:
void ThreadFunc()
{
// Loop is required, otherwise thread will exit
for (;;)
{
bool read = false;
int value;
{
std::lock_guard<std::mutex> lock(m);
if (queue.size())
{
value = queue.front();
read = true;
queue.pop_back();
}
}
if (read)
{
// send(header.data(), header.dataSize());
// send(proto.data(), proto.dataSize());
printf("Hello %dn", value);
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void TestFunc()
{
std::thread thread(std::bind(&Test::ThreadFunc, this));
thread.detach();
int i = 0;
// Loops only as a test example
for (;;)
{
std::lock_guard<std::mutex> lock(m);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
queue.push_back(i++);
// Queue Message(header, payload);
}
}
};
int main()
{
Test test;
test.TestFunc();
}
将std::thread thread(ThreadFunc);
改为std::thread thread(Test::ThreadFunc, this);
相关文章:
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 通过安装信号处理程序关闭多线程应用程序
- 多线程减慢程序速度:无错误共享,无互斥锁,无缓存未命中,无小工作量
- C++多线程程序:变量定义为类成员的隔离错误
- 多线程 gtkmm 应用程序最简单的示例
- 将数组作为多线程应用程序中函数的返回传递
- 修改多线程应用程序中的对象
- 在以读取为主的多线程程序中,可以使用原子来减少锁定吗
- 多线程程序中的分段故障和gdb回溯上的不完整信息
- 多线程程序卡在优化模式下,但在 -O0 中正常运行
- 多线程 C++11 应用程序中的同步
- 多线程Windows GUI应用程序中的死锁
- 在使用 std::cout 和多线程程序中如何避免数据竞争<iomanip>?
- 控制多线程程序中的输出流
- C++多线程应用程序将永远挂起
- 具有多线程应用程序的 Nanomsg 无阻塞双向套接字
- C++从多线程 CPU 程序迁移到 GPU
- C++应用程序多线程中的锁定方法