函数用于c++中类中的线程
Function for the thread within a class in C++
我在创建函数时遇到了麻烦,应该处理新线程。当我在类外创建它时,一切正常,但当我想在类内创建它时,我不知道如何调用它。
我调用函数:
pthread_t thread;
pthread_create(&thread, NULL,
sendMessage, (void *) fd);
和函数本身是这样的:
void * sendMessage(void *threadid) {
string message;
const char * c;
char buffer[200];
int fd = (long) threadid;
while (true) {
cin >> message;
if (message == "exit") {
break;
}
c = message.c_str();
strncpy(buffer, c, sizeof ( buffer));
send(fd, buffer, strlen(buffer), 0);
}
}
但是当我在一个类中声明它时,例如void * Client::sendMessage(void *threadid)
,我甚至不能构建它,因为我得到main.cpp:90:37: error: argument of type ‘void* (Client::)(void*)’ does not match ‘void* (*)(void*)’
。有没有人知道,什么会导致它以及如何修复它?
只是std::thread
如何快速使您的所有问题消失的快速演示(通过无缝集成std::bind
样式调用):
#include <string>
#include <thread>
#include <memory>
void some_function(int i, std::string bla)
{
}
struct some_class
{
void some_member_function(double x) const
{
}
};
int main()
{
std::thread t1(&some_function, 42, "the answer");
std::thread t2;
{
some_class instance;
t2 = std::thread(&some_class::some_member_function,
std::ref(instance),
3.14159);
t2.join(); // need to join before `instance` goes out of scope
}
{
auto managed = std::make_shared<some_class>();
t2 = std::thread([managed]()
{
managed->some_member_function(3.14159);
});
// `managed` lives on
}
if (t1.joinable()) t1.join();
if (t2.joinable()) t2.join();
}
相关文章:
- C++使用params创建线程函数会导致转换错误
- 如何在大函数中编写多线程函数?
- C++11:将矢量元素作为线程传递到线程函数中
- 线程函数中的c++参数更改
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- 将项目插入 CTreeCtrl 时线程函数的奇怪行为
- C++ 线程函数通过引用传递
- 线程函数参数的前向声明不起作用
- 线程函数无法从堆上分配的缓冲区中读取字符
- 线程函数不打印
- C :如何在复杂模板类中指定线程函数
- 为什么我在C++线程函数调用中得到重复值?
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 线程函数中的通用引用
- 如何同时启动两个具有不同线程函数的线程团队
- std::c++ 中的线程在设置线程函数时不会出错
- 对抽象类的引用不能传递给线程函数?
- 如何将ifstream作为参数传递给std ::线程函数
- 如何线程函数