【问题标题】:Executing a particular statement in intervals in C while other statement keeps running在 C 中以间隔执行特定语句,而其他语句继续运行
【发布时间】:2015-05-14 16:18:24
【问题描述】:

可以吗?

我要执行以下语句...

while(1){
    fputs(ch, b);
    printf("Extracting information please wait..."); //This is the line I want to execute in intervals
}

在 C 中可以这样做吗? 我尝试保留一个 x 变量以使打印语句执行得更慢,如下所示:

while(1){
   fputs(ch, b);
   if(x%10 == 0)
      printf("...");
   x++;
}

但显然它会使文件填充的执行速度变慢。有什么办法吗?我知道很可能没有,因为 C 逐行执行,因为它不是脚本语言,但仍然如此。我们可以为此目的使用 sleep() 吗?还是唯一的方法是让两个语句都等待?

【问题讨论】:

  • C 还是 C++?对于不同的语言,答案是不同的,您同时标记了这两种语言。
  • 是的,那是因为我想,即使是 C++ 程序员也能回答,我想要 C。
  • 这是一个典型的多线程问题。这意味着它需要多线程解决方案。否则主线程会被打断,拖慢程序速度。
  • 线程或setitimer,我怀疑setitimer 不是你的解决方案,因为在信号处理程序中你可以做的很少。
  • 我从来没有在 C 中做过多线程...thanx...我会检查一下.....

标签: c sleep time.h


【解决方案1】:

我整理了一个示例代码,我认为可能会对您有所帮助。

下面的代码使用一个名为 pthread 的库来完成工作。

请注意,它适用于 linux,我不确定它是否适用于其他操作系统。


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 
#include <pthread.h>

void * thread1(void* arg)
{
    while (i)
    {
        printf("Extracting information please wait...\n");
        fflush(stdout);
        sleep(1);
    }
    return (void *) 0;
}

int main(void) {

    //declaring the thread variable -- will store the thread ID
    static pthread_t pthread1;

    //creates the thread 'thread1' and assing its ID to 'pthread1'
    //you could get the return code of the function if you like
    pthread_create(&pthread1, NULL, &thread1,NULL);

    // this line will be written once and would be the place to run the command you want
    printf("You could start fgets now!! remember to put it after the creation of the thread\n");
    fflush(stdout);

    // since I am not writing anything to the file stream I am just waiting;
    sleep(10);
    return EXIT_SUCCESS;
}

希望对你有帮助。

【讨论】:

  • 是的,它在 Windows 上不起作用……它在 linux 上起作用,Windows 使用 windows.h 库进行多线程处理……无论如何,谢谢 :)
  • @bayblade567,您是否尝试过在线程内使用信号量?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多