使用线程实现进度控制

发布于 2024-08-27 08:45:59 字数 172 浏览 1 评论 0原文

我对 C 中的线程概念很陌生,所以我发现很难实现它 在我的职能中。我有一个简单的应用程序,我想在其中显示进度条 特定的地方。在一个特定的函数中,我将读取文件(在 for 循环中)进行一些操作(关于我的应用程序)。当它读取文件时,我想显示一个进度条,表明它正在读取文件。我知道应该使用线程的概念来完成,但我不太确定如何做到这一点。

I am new to the concept of threading in C, so I find it difficult to implement that
in my function. I have a simple application in which I want to display a progress bar at a
particular place. In a particular function I will read files(in a for loop) for some manipulations(regarding my application). While it's reading the files I want to display a progress bar, stating that it's in process of reading files. I know it should be done using the concept of threading, but I am not quite sure how to do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

电影里的梦 2024-09-03 08:45:59

在主程序中创建一个工作线程并设置执行文件处理的回调例程。
该例程还将计算完成的百分比。每当该百分比发生变化时,发布
值作为窗口消息,主线程将捕获并更新进度条控件。
您可以定义应用程序内部消息,例如 #define MSG_PROGRESS_VALUE (WM_USER + 1)

编辑:样本,

#define MSG_PROGRESS_VALUE (WM_USER + 1)
#define MSG_WORKER_DONE    (WM_USER + 2)
...
DWORD WINAPI  jobroutine(LPVOID lpParameter) {
   while (TRUE) {
      // process files ...
      // calculate new percent
      if (newpercent != oldpercent) {
         PostMessage(mainwnd, MSG_PROGRESS_VALUE, 0, newpercent);
         oldpercent = newpercent;
      }
      ...
   }
   PostMessage(mainwnd, MSG_WORKER_DONE, 0, 0);
   return 0;
}
...
MainWndProc(...)  {
   switch (uMsg) {
   ...
   case MSG_PROGRESS_VALUE:
   // update progress bar value (lParam)
   break;
 ...
}
...
WinMain(...) {
   HANDLE worker = CreateThread(NULL, 0, jobroutine, NULL, NULL, NULL);
   ...
   // Start classic windows message loop
   ...
}

Create a worker thread in the main program and set the callback routine that does the file processing.
That routine also will calculate the percentage that is completed. Whenever that percent changes, post the
value as a window message which the main thread will catch and update the progress bar control.
You can define application inner messages like #define MSG_PROGRESS_VALUE (WM_USER + 1).

Edit: sample,

#define MSG_PROGRESS_VALUE (WM_USER + 1)
#define MSG_WORKER_DONE    (WM_USER + 2)
...
DWORD WINAPI  jobroutine(LPVOID lpParameter) {
   while (TRUE) {
      // process files ...
      // calculate new percent
      if (newpercent != oldpercent) {
         PostMessage(mainwnd, MSG_PROGRESS_VALUE, 0, newpercent);
         oldpercent = newpercent;
      }
      ...
   }
   PostMessage(mainwnd, MSG_WORKER_DONE, 0, 0);
   return 0;
}
...
MainWndProc(...)  {
   switch (uMsg) {
   ...
   case MSG_PROGRESS_VALUE:
   // update progress bar value (lParam)
   break;
 ...
}
...
WinMain(...) {
   HANDLE worker = CreateThread(NULL, 0, jobroutine, NULL, NULL, NULL);
   ...
   // Start classic windows message loop
   ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文