在C++中模拟Java的Thread类
Simulate Java's Thread class in C++
我正试图在C++中创建自己的Thread类,该类类似于Java Thread对象。我知道C++不使用实现,所以我在C++线程对象中保留了对函数的引用作为变量。
我在线程对象的第二个构造函数中遇到了问题,作为线程对象的用户,您需要指定自己要运行的函数。
我收到一条信息,上面写着
线程.cpp:23:58:错误:从"void()(void
#ifndef THREAD_H
#define THREAD_H
#include <iostream>
#include <pthread.h>
#include <cstdlib>
#include <string.h>
class Thread
{
public:
Thread();
Thread(void (*f)(void*));
~Thread();
void* run(void*);
void start();
private:
pthread_t attributes;
int id;
void (*runfunction)(void*); //Remember the pointer to the function
};
void* runthread(void* arg); //header
#endif
这是我的C++文件
#include "Thread.h"
Thread::Thread()
{
memset(&attributes,0,sizeof(attributes));
}
Thread::Thread(void (*f)(void*))
{
runfunction = f;
//(*f)();
}
Thread::~Thread()
{
id = pthread_create(&attributes, NULL, runthread,this);
}
void Thread::start()
{
memset(&attributes,0,sizeof(attributes));
id = pthread_create(&attributes, NULL, *runfunction,this);
}
void* Thread::run(void*)
{
}
void* runthread(void* arg)
{
Thread* t = (Thread*) arg;
t->run(NULL);
}
pthread_create
需要一个函数,其中一个void*
参数返回void*
,而您提供的函数返回void
。
但是,正如评论所说,使用C++内置线程是更好的选择。
相关文章:
- 在java中解决这段代码时面临循环中的问题
- 尝试用java代码编译和运行c++代码
- 在std::thread中,joinable()然后join()线程安全吗
- 在这种情况下,java对象是否可以调用本机函数
- 在java中读取c++字节的位字段
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 分离一个静态常量 std::thread?
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 使用已使用 java 编码的 openssl 解码数据
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- SWIG Java 在使用 -DSWIGWORDSIZE64 时将int64_t转换为 jlong
- 如何从 std::thread 返回值
- Android Java USB for native cpp
- 在C++中使用并行化的预期速度是多少(不是 OpenMp,而是 <thread>)
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- C++ equivalent to Java Map getOrDefault?
- C++ 中的 Java 样式枚举
- 在C++中模拟Java的Thread类