可以使用pthread库来创建线程,并使用pthread_join函数来等待线程结束。在主线程中使用while循环来保持打印,同时在循环中使用pthread_create函数来创建新的线程并执行一些内容,然后使用pthread_join函数等待线程结束。待线程执行完毕后,重复执行该线程即可。

以下是一个简单的示例代码:

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

void *thread_func(void *arg)
{
    printf("Thread is running...\n");
    // 执行一些任务
    printf("Thread is done.\n");
    pthread_exit(NULL);
}

int main()
{
    pthread_t thread_id;
    int ret;

    while (1) {
        printf("Main thread is running...\n");

        // 创建新线程
        ret = pthread_create(&thread_id, NULL, thread_func, NULL);
        if (ret != 0) {
            printf("Error: pthread_create failed.\n");
            return -1;
        }

        // 等待线程结束
        pthread_join(thread_id, NULL);

        printf("Main thread is done.\n");
    }

    return 0;
}

在上述代码中,while循环会一直运行,不断创建新线程并等待其结束,然后重复执行。线程函数thread_func中执行一些任务,然后调用pthread_exit退出线程。在创建线程时使用pthread_create函数,创建新线程并传入线程函数和参数。在等待线程结束时使用pthread_join函数,等待线程结束并清理资源。

c语言如何在主线程保持循环打印同时打印创建一个新的线程执行一些内容待创建的线程执行完重复执行该线程

原文地址: https://www.cveoy.top/t/topic/qMG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录