【问题标题】:Using pthread for a while(1) loop in c++?在 c++ 中使用 pthread 进行 while(1) 循环?
【发布时间】:2014-11-04 21:51:12
【问题描述】:

我有一个关于如何更改我在 C++ 中编写的程序的问题 如下图。

实际上我的程序开始了。如果我想启动该功能,例如test::test1 这是一个永远不会结束的while(1)循环,循环下面的程序永远不会运行。

所以我搜索了很多,我找到了主题 pthread 来解决我的问题。

但我真的不知道,如何更改我的程序...

我有以下文件:

main.cpp
test.h
test.cpp

这是test.cppwhile(1)-Loop out 函数save() 将打开一个数据库并保存值1-3、时间、日期。 我希望在主程序初始化类测试时启动函数test::test1()

有人知道如何更改我的程序吗?

 void test::test1()
    {


        double i = 1;

    while(1)
    {

        i=i;
        save(i, value1(), value2(), value3(), time(), date());
        i++;

        usleep( DELAY * 1000000 );

    }

Here is my image
http://abload.de/img/unbenanntfquwl.png

【问题讨论】:

  • 我不太确定你想达到什么目标。你想把 test::test1() 撕成一个 pthread 吗?
  • C++ 有自己的线程,std::thread,你应该默认使用它。在线搜索相应教程或在此处讨论。

标签: c++ class pthreads


【解决方案1】:

如果您真的仅限于 pthreads,以下可能会有所帮助。

#include <pthread.h> 
#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <unistd.h> 

class test { 
public: 
    void save(...) {}; 
    void test1() { 
        double i = 1; 

        while(true) 
        { 
            save(i, 0, 0, 0, 0, 0); 
            i++; 

            std::cerr << " ** " << std::endl; 
            usleep( 1000000 ); 

        } 
    } 

    static void * run(void * arg ) { 
        ((test *)arg)->test1();
        return NULL; 
    } 
}; 


int main() 
{ 
    pthread_t thr; 
    test tst; 
    pthread_create(&thr, NULL,test::run,&tst); 
    pthread_join(thr,NULL); 
    return 1; 
} 

运行 pthread 最重要的部分是指向 C 风格函数的指针,该函数采用 void * 参数。非静态 C++ 成员函数总是将 this 作为隐藏参数,因此它们不是 pthread 的直接候选者。我总是创建一个静态 run(...) 方法,该方法显式获取指向对象的指针并将调用转发给非静态成员函数。

如果允许您使用更现代的 C++ 功能,我会关注 @Ulrich Eckhardt 并使用 std::thread 构造。

PS:在 run(...) 中添加了缺少的 retun 语句

【讨论】:

  • 您好 Oncaphillis,感谢您的评论。我将您的源代码复制到我的程序中,但编译器显示:|26|error: expected constructor, destructor, or type conversion before '(' token| 第 26 行如下: pthread_create(&thr, NULL,test::run, &tst); 对您的源代码的另一个问题。我是否必须将 while(true)-loop 放入头文件中,就像您在代码中所做的那样?
  • @jollepe 在我位于 run(...) 的第 26 行中,只有一个缺少的 return 语句,我的 gcc 默默地接受了它。我已经更新了代码,它运行良好。当然,您必须与 pthread 库链接。我没有将循环放入标题中,它是基于您的示例的自包含代码块。布局完全取决于您。本质上 pthread_create 只需要知道要运行的函数的地址。
  • 我将您的更正复制到我的程序中。但尽管如此,该程序无法编译。我的第 26 行是以下代码行: pthread_create(&thr, NULL,messen::run,&tst);我在我的 int main() 开头复制了这段代码,但是在类的初始化之后。 pthread_t thr;消息 tst; pthread_create(&thr, NULL,messen::run,&tst); pthread_join(thr,NULL);添加 test.cpp : static void * run(void * arg ) { ((messen *)arg)->messung();返回空值;因此我将这段代码复制到 test.h static void * run(void * arg );
  • @jollepe 真的很难理解你做了什么,但因为它是我的代码运行。如果您将我的代码粘贴到您的程序中,则很难理解您的第 26 行可能是什么。
猜你喜欢
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 2013-02-13
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多