c语言如何在主线程保持循环打印同时打印创建一个新的线程执行一些内容
可以使用pthread_create函数创建一个新的线程,该线程执行一些内容,同时在主线程中使用while循环保持打印输出。
下面是示例代码:
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg)
{
printf("New thread is running...\n");
// 执行一些内容
return NULL;
}
int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, thread_func, NULL);
if (ret != 0) {
printf("Create thread error!\n");
return 1;
}
printf("Main thread is running...\n");
while (1) {
printf("Hello, world!\n");
// 主线程循环打印输出
sleep(1);
}
return 0;
}
在上述代码中,主线程使用while循环打印输出,并创建了一个新的线程执行thread_func函数中的内容。注意,创建线程时需要使用pthread_create函数,并传递线程函数和参数。同时,需要使用pthread_t类型的变量保存线程ID,以便后续操作。
原文地址: https://www.cveoy.top/t/topic/qMg 著作权归作者所有。请勿转载和采集!