C 程序未在 main() 中休眠

标签 c multithreading sleep

我试图强制我的程序在创建线程后休眠一秒钟。我可以让线程在其进程中休眠,但不能在主线程中休眠。我读到的所有内容都表明它只是一个系统进程,无论在哪里调用它都应该工作。我希望它在打印线程已创建后(在连接之前)休眠。 “创建”和“加入并退出”打印语句之间没有延迟。你能说出为什么它不起作用吗?

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

#define SECONDS   1     //seconds to sleep
#define SIZE     25     //number of fibonaccis to be computed

int *fibResults;        //array to store fibonacci results
int  idx;               //index for the threads

//executes and exits each thread
void *run(void *param) {
  if (idx == 0) {

    sleep(SECONDS);
    fibResults[idx] = 0;
    pthread_exit(0);

  } else if (idx == 1) {

    sleep(SECONDS);   
    fibResults[idx] = 1;
    pthread_exit(0);   

  } else {

    sleep(SECONDS);
    fibResults[idx] = fibResults[idx -1] + fibResults[idx -2];
    pthread_exit(0);

  }
}


int main(void) {
  fibResults = malloc(SIZE * sizeof(*fibResults));
  pthread_attr_t attrs;
  pthread_attr_init(&attrs);

  for (idx = 0; idx < SIZE; idx++) {
    pthread_t thread;
    pthread_create(&thread, &attrs, run, NULL);

    printf("Thread[%d] created\t", idx);

    sleep(SECONDS); //THIS IS WHERE SLEEP ISN'T WORKING!!!!!!!!!!!!!

    pthread_join(thread, NULL);

    printf("Thread[%d] joined & exited\t", idx);
    printf("The fibonacci of %d= %d\n", idx, fibResults[idx]);
  }
  return 0;
}

最佳答案

for (idx = 0; idx < SIZE; idx++)
{
  pthread_t thread;
  pthread_create(&thread, &a, run, NULL);
  printf("Thread[%d] created\t", idx);
  fflush(stdout);
  sleep(SECONDS);
  pthread_join(thread, NULL);
  printf("Thread[%d] joined & exited\t", idx);
  printf("The fibonacci of %d= %d\n", idx, fibResults[idx]);
}

关于C 程序未在 main() 中休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53423194/

相关文章:

c - 天真的指针算术合并排序返回错误

multithreading - 如何在不等待另一个 goroutine 中设置的情况下读取 channel ?

java - 程序在 Thread.sleep() 期间和计时器卡住

java - 如何同时显示启动屏幕和我的 JFrame?

windows - 为什么我要使用无限超时的 Sleep()?

c - 读取数据并使用 scanf 跳过括号

c - 内核编程

c++ - 如何正确使用_beginthread和endthread

python - 如何运行多线程Python脚本

c - c 如何允许不传递所有参数?