C语言实现多线程循环打印ABC (50次)
#include <stdio.h>\n#include <pthread.h>\n\npthread_mutex_t mutex;
pthread_cond_t cond;
\nvoid* printA(void* arg) {
int count = ((int)arg);
int i;
\n for (i = 0; i < count; i++) {
pthread_mutex_lock(&mutex);
while (i % 3 != 0) {
pthread_cond_wait(&cond, &mutex);
}
printf("A");
fflush(stdout);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
\n return NULL;
}\n\nvoid* printB(void* arg) {
int count = ((int)arg);
int i;
\n for (i = 0; i < count; i++) {
pthread_mutex_lock(&mutex);
while (i % 3 != 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("B");
fflush(stdout);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
\n return NULL;
}\n\nvoid* printC(void* arg) {
int count = ((int)arg);
int i;
\n for (i = 0; i < count; i++) {
pthread_mutex_lock(&mutex);
while (i % 3 != 2) {
pthread_cond_wait(&cond, &mutex);
}
printf("C");
fflush(stdout);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
\n return NULL;
}\n\nint main() {
pthread_t t1, t2, t3;
int count = 50;
\n pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
\n pthread_create(&t1, NULL, printA, &count);
pthread_create(&t2, NULL, printB, &count);
pthread_create(&t3, NULL, printC, &count);
\n pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
\n pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
\n return 0;
}\n\n在这个例子中,我们创建了三个线程,分别负责循环打印字母 A、B、C。使用互斥锁 mutex 和条件变量 cond 来实现线程间的同步。每个线程在打印自己的字母之前,会先检查 i 的值来确定是否轮到自己打印,如果不是则调用 pthread_cond_wait() 进入等待状态。当条件满足时,调用 pthread_cond_signal() 唤醒其他线程,并释放互斥锁 mutex,然后打印自己的字母。最后,主线程调用 pthread_join() 来等待三个线程的结束。
原文地址: https://www.cveoy.top/t/topic/p9fY 著作权归作者所有。请勿转载和采集!