pthread_在C+中创建错误+;(类内的pthread) < P>我有这个C++代码,我尝试创建一个pTrk,我得到了4个错误:
有人能帮忙吗 提前谢谢pthread_在C+中创建错误+;(类内的pthread) < P>我有这个C++代码,我尝试创建一个pTrk,我得到了4个错误:,c++,linux,pthreads,C++,Linux,Pthreads,有人能帮忙吗 提前谢谢 #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <iostream> static void* func(void*); class Test { public: pthread_t *threadId; pthread_create(threadId, NULL, func, NULL); }; stat
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
static void* func(void*);
class Test
{
public:
pthread_t *threadId;
pthread_create(threadId, NULL, func, NULL);
};
static void* func(void *arg)
{
printf("Thread function called\n");
}
int main()
{
Test();
}
如果我将thread函数用作“C”链接:
面临的错误是:
simplepThread.cc:7: error: previous declaration of ‘void* func(void*)’ with ‘C++’ linkage
simplepThread.cc:15: error: conflicts with new declaration with ‘C’ linkage
不能在类声明中调用函数。在类声明中,您只能声明(并可能定义)其成员。及
pthread_create(threadId, NULL, func, NULL);
不是有效的成员函数定义。整个类测试似乎是多余的
static void* func(void *arg)
{
printf("Thread function called\n");
}
int main()
{
pthread_t threadId;
pthread_create(&threadId, NULL, func, NULL);
}
应该很好。我还修复了另一个问题-您试图将未初始化的指针(
threadId
)传递给需要变量地址的函数。更新
关于链接-您有一个默认的原型(C++链接) 用C键定义和定义
extern "C"
{
void* func(void *arg)
{
....
}
}
所以他们互相冲突。将原型更改为
extern "C"
{
void* func(void *arg);
}
这样就没问题了您的代码有很多问题。首先,您需要为测试类声明一个构造函数,并给出代码的使用方法,我会将pthread_create()调用放在构造函数中。其次,pthread_create()将pthread_t*参数作为其第一个参数,这意味着该参数将用作输出参数,指针应指向实际内存/变量,新创建线程的线程ID将放置在该内存/变量中
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
static void* func(void*);
class Test
{
public:
pthread_t threadId;
Test() {
pthread_create(&threadId, NULL, func, NULL);
}
};
static void* func(void *arg)
{
printf("Thread function called\n");
}
int main()
{
Test();
}
#包括
#包括
#包括
#包括
静态void*func(void*);
课堂测试
{
公众:
pthread_t threadId;
测试(){
pthread_create(&threadId,NULL,func,NULL);
}
};
静态void*func(void*arg)
{
printf(“调用线程函数\n”);
}
int main()
{
Test();
}
一般来说,在执行多线程代码时,还需要确保线程在使用完后被销毁,或者跟踪线程自行死亡的时间。例如,如果您创建一个“工作线程”,该线程将用于在后台异步处理工作,那么您通常需要一个受互斥保护的队列,以便主线程将工作传递给工作线程。您通常还需要一些信号量或其他“安全”的信号系统,以便在程序想要退出时使工作线程安全地死亡,并使用反向信号机制,以便主线程知道工作线程何时死亡,现在清理共享数据结构是安全的。(也就是说,将一件简单地写着“死亡”的工作放入工作队列,并让工人在退出前回答“死亡”)
实现正确的多线程代码并非易事,您必须担心一系列问题,例如死锁和争用条件,这些问题在单线程代码中根本不会发生。我强烈建议您阅读并确保完全理解这些主题和其他主题。为什么要在类声明中调用函数?我的设计要求,解决方案是什么。我会纠正这个吗?@金斯马赫:这不是有效的C++。Word中的设计要求是什么?我需要创建pTrk,将在C++构造函数中完成它。我实际上是在设计一个计时器。@Kenny,是的..工作正常。我忘记了基础知识:(谢谢,是的,在我在类构造函数中声明它之后,它就解决了。事实上,我忘记了基础知识:(。但是,你的“C”链接原型声明非常有用。再次感谢。
extern "C"
{
void* func(void *arg)
{
....
}
}
extern "C"
{
void* func(void *arg);
}
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
static void* func(void*);
class Test
{
public:
pthread_t threadId;
Test() {
pthread_create(&threadId, NULL, func, NULL);
}
};
static void* func(void *arg)
{
printf("Thread function called\n");
}
int main()
{
Test();
}