c - 在 C 中以间隔执行特定语句,而其他语句保持运行

标签 c sleep time.h

有可能吗?

我要执行以下语句...

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() 吗?或者唯一的方法是让两个语句都等待?

最佳答案

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

下面的代码使用一个名为 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;
}

希望对您有所帮助。

关于c - 在 C 中以间隔执行特定语句,而其他语句保持运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30242235/

相关文章:

c - 如何设计一个信号安全的 shell 解释器

c++ - QThread::sleep() 是否需要运行事件循环?

linux - clock_gettime() 不起作用

c++ - 在 C++ 中验证出生日期

c++ - 是否有任何理由在 C 中声明 "volatile const"而在 C++ 中仅声明 "volatile"?

c - 'closeapp' 未在此范围内声明

linux - 为什么在 Linux 中做 I/O 是不间断的?

在指定时间(以毫秒为单位)后停止的 C 函数

c - 我如何在 C 中解决给定的 typedef

c - C 中是否有 sleep() 的替代方案?