分析下面代码的每一步功能:#include <stdio.h> #include <pthread.h> #define QUEUE_SIZE 20 #define THREAD_NUM 10 #define MAX_NUM 30000200 #define MIN_NUM 30000000 int queue[QUEUE_SIZE]; int front = 0; int rear = 0; int finished = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int is_prime(int num) { int i; if (num <= 1) { return 0; } for (i = 2; i * i <= num; i++) { if (num % i == 0) { return 0; } } return 1; } // 子线程函数 void *thread_func(void arg) { int thread_num = (int)arg; while (1) { pthread_mutex_lock(&mutex); while (front == rear && finished == 0) { pthread_cond_wait(&cond, &mutex); } if (front == rear && finished == 1) { pthread_mutex_unlock(&mutex); break; } int num = queue[front++]; if (front == QUEUE_SIZE) { front = 0; } pthread_mutex_unlock(&mutex); if (is_prime(num)) { printf("Thread %d: %d\n", thread_num, num); } } pthread_exit(NULL); } int main() { int i, j; pthread_t tids[THREAD_NUM]; int thread_num[THREAD_NUM]; for (i = 0; i < THREAD_NUM; i++) { thread_num[i] = i; pthread_create(&tids[i], NULL, thread_func, (void)&thread_num[i]); } for (i = MIN_NUM; i <= MAX_NUM; ) { pthread_mutex_lock(&mutex); if ((rear + 1) % QUEUE_SIZE == front) { pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); continue; } queue[rear++] = i++; if (rear == QUEUE_SIZE) { rear = 0; } pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } pthread_mutex_lock(&mutex); finished = 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); for (i = 0; i < THREAD_NUM; i++) { pthread_join(tids[i], NULL); } return 0; }
时间: 2024-04-04 09:35:21 浏览: 109
这段代码是使用多线程实现素数的查找。整个程序的流程如下:
1. 定义了一些常量和全局变量,如队列大小、线程数、素数查找的范围、队列、队列头尾指针、线程完成标志、互斥锁和条件变量。
2. 定义了一个判断某个数是否为素数的函数is_prime。
3. 定义了一个子线程函数thread_func,该函数是每个线程要执行的操作,即从队列中取出一个数,判断该数是否为素数,如果是,则输出该数和线程号。
4. 在主函数中,创建了多个子线程,并将每个线程的编号作为参数传递给线程函数。
5. 在主函数中,将要查找的数依次加入到队列中,每加入一个数就通过条件变量唤醒一个等待的线程来处理。
6. 在主函数中,等待所有线程执行完毕。
整个程序的关键在于通过条件变量和互斥锁实现线程之间的同步,使得每个线程都能够从队列中取出一个数并进行处理。同时,为了防止队列溢出,需要在队列满时阻塞等待,直到队列有空位才能继续添加数。
阅读全文