C - 如何运行一个线程几秒钟,然后继续第二个线程



>我正在开发我的程序,我希望线程 1 运行 2.1 秒,2.1 秒后我希望线程 2 运行 3.4 秒,然后它需要切换回线程 1。我已经设法让两个线程都运行,但没有给定的时间。我需要使用 2 个线程。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int main() {
void* taskOne();
void* taskTwo();
pthread_attr_t tattr;
pthread_attr_init(&tattr);
pthread_t thread1, thread2;
double seconds1 = 2.1;
double seconds2 = 3.4;

pthread_create(&thread1, &tattr, taskOne, NULL);
pthread_create(&thread2, &tattr, taskTwo, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
void* taskOne() {
int i, j, m, n;
while (1) {
for (i = 0; i < 5; i++) {
for (j = 1; j <= 8; j++) {
printf("thread: 1 periodnumber: %in", j);
for (m = 0; m <= 1250; m++)
for (n = 0; n <= 250000; n++);

}
}
}
}
void* taskTwo() {
int i, j, m, n;
while (1) {
for (i = 0; i < 5; i++) {
for (j = 1; j <= 8; j++) {
printf("thread: 2 periodnumber: %in", j);
for (m = 0; m <= 2750; m++)
for (n = 0; n <= 250000; n++);

}
}
}
}

您可以通过调用 sleep(( 函数使线程在任何时间休眠,但这是"休眠 x 秒"而不是"休眠 x 秒"。

我能想到的实现这一点的唯一方法是在你的线程之外运行一个计时器,让它们在所需的时间内暂停((,然后发送一个非终止信号,当你再次需要它时唤醒它。

sleep(n( 可以工作,但只处理整数。

此外,当您尝试暂停/休眠时,无法保证您的线程不会忙于阻塞 I/O,因此,如果这实际上完全按照您想要的方式发生非常重要,则需要做一些工作来防止阻塞。

让我重新表述一下你的问题:你希望你的程序在 2.1 秒内做一件事,然后你希望它停止做那件事,做其他事情 3.4 秒,然后你希望它回到做第一件事。

您不需要多个线程。您所需要的只是一种让两个函数查看时钟的方法。

#include <time.h>
do_thing_1(double for_how_long) {
struct timespec start_time;
clock_gettime(CLOCK_MONOTONIC, &start_time);
while (elapsed_time_since(&start_time) < for_how_long) {
...
}
}
do_thing_2(double for_how_long) {
struct timespec start_time;
clock_gettime(CLOCK_MONOTONIC, &start_time);
while (elapsed_time_since(&start_time) < for_how_long) {
...
}
}
main(...) {
do_thing_1(2.1 /*seconds*/);
do_thing_2(3.4 /*seconds*/);
do_thing_1(9999999.9);
}

留给读者练习:实施elapsed_time_since(...)

额外学分:编写一个通用do_thing(function, for_how_long)函数。

最新更新