在FLTK中进行线程化

问题描述 投票:0回答:1

首先,我回顾了test/threads.cxx的例子;但它并不完全是我正在寻找的用例,因为示例线程函数可以访问FLTK函数。

我有一个libssh2库函数(我写的,但不喜欢它不依赖于FLTK),具有以下函数头:

int sshSendFile(const char * loclfile,const char * scppath,char * bytesuploaded)

我希望这个在一个线程中运行,而在线程中,FLTK旋转并读取值bytesupload并更新Fl_Progress上的标签,当然sshSendFile在上传时正在更新。

实际上,到目前为止,这就是我所拥有的;一旦sshSendFile完成,我的程序最终退出Debug!

            Fl::lock();

            char * string_target;

            string_target = (char *)malloc(128);

            void * next_message;

            (Fl_Thread)_beginthread((void(__cdecl *)(void *))sshSendFile("C:/randomfile.txt", "/tmp/testing, string_target), 0,NULL);

            while (Fl::wait() > 0) {
                if ((next_message = Fl::thread_message()) != NULL) {
                    this->progress_bar->label(string_target);
                    this->redraw();
                    Fl::check();
                }
            }

            Fl::unlock();

Fl:wait()设置断点永远不会被击中。我在调试这个问题时遇到了一些麻烦,发现文档并不太清楚。任何帮助表示赞赏!

c++ fltk
1个回答
1
投票

您在主线程中调用sshSendFile然后尝试使用此函数的结果启动线程。

请注意,_beginthread接受指向函数的指针,你必须使用从int(void(__cdecl *)(void *))的这个丑陋的演员“沉默”错误。

换句话说,您必须将函数指针作为第一个参数传递给_beginthread,最简单的方法是创建“thread main”,如下所示:

struct Task {
    std::string file;
    ...
}

void sendFiles(void* arg) {
      Task* task = (task*)arg;
      sshSendFiles(task.file.c_str(), ...); 
      delete task;
}

和你的启动线程的代码,应该通过这个sendFiles和一个任务指针:

task* task = new task();
task->file = "something";
... initialize also buffer
(Fl_Thread)_beginthread(&sendFiles, 0, task);
   // this will call startThread(task) in main thread

另一方面,使用C ++ 11中的现代线程api要容易得多,因为你现在所做的是简单的旧系统级别C,它复杂,不方便,最好不要使用。

© www.soinside.com 2019 - 2024. All rights reserved.