c - C 程序不在 main() 中休眠
问题描述
我试图强制我的程序在创建线程后休眠一秒钟。我可以让线程在其进程中休眠,但不能在主线程中休眠。我读到的一切都说它只是一个系统进程,应该在任何地方工作。我希望它在打印线程已创建后(在加入之前)休眠。“创建”和“加入和退出”打印语句之间没有延迟。你能说出为什么它不起作用吗?
#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]);
}
推荐阅读
- amazon-web-services - 对 AWS 资源实施标记
- json - 如何使用 Vapor Websockets 向客户端发送字典
- vim - 如何删除高亮组?
- three.js - 将 Vector3 与 BoxBuffer 几何连接以使用 Threejs 进行适当的角度连接
- postgresql - 并行读取数据时,Spark 不会将过滤器下推到 PostgreSQL 数据源,提供下限和上限的值
- github - Github Enterprise Private repo 访问
- node.js - Sequelize不在postgresql中创建任何表
- react-native - 跟踪用户从网页到应用安装和打开
- java - 使用迭代器从 Java 集合中删除元素
- javascript - javascript:在 onchange 函数中传递数组