c语言启动一个线程进行一定操作主线程等待创建的线程执行完后再次执行该线程在主线程打印线程执行的次数死循环该过程
以下是一个简单的示例代码:
#include <stdio.h>
#include <pthread.h>
void* thread_function(void* arg) {
int num_executions = *(int*) arg;
for (int i = 1; i <= num_executions; i++) {
printf("Thread execution %d\n", i);
}
pthread_exit(NULL);
}
int main() {
int num_executions = 5;
pthread_t thread;
pthread_create(&thread, NULL, thread_function, &num_executions);
pthread_join(thread, NULL);
while (1) {
printf("Main thread\n");
pthread_create(&thread, NULL, thread_function, &num_executions);
pthread_join(thread, NULL);
}
return 0;
}
在这个示例中,我们创建了一个名为 thread_function 的函数作为线程执行的入口点。该函数接收一个整数作为参数,表示线程应该执行的次数。在函数内部,我们使用一个简单的循环来打印线程执行的次数。
在 main 函数中,我们首先创建一个线程并等待其执行完毕。随后,我们进入一个无限循环,在每次迭代中创建一个新的线程并等待其执行完毕。在每个线程执行完毕后,我们会在主线程中打印一条消息,以便我们可以看到线程执行的次数。
请注意,由于 thread_function 函数接收一个指向整数的指针作为参数,因此我们需要使用 &num_executions 将整数的地址传递给 pthread_create 函数。同样,我们在调用 pthread_join 函数时传递了 NULL,因为我们不需要从线程中返回任何值。
在实际编程中,应该注意避免无限循环。
原文地址: http://www.cveoy.top/t/topic/qFa 著作权归作者所有。请勿转载和采集!