以下是用 C 语言实现的代码:

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

pthread_mutex_t mutex;
pthread_cond_t cond;

void* printABC(void* arg) {
    int count = *((int*)arg);
    int i;

    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);
    }

    return NULL;
}

void* printABC(void* arg) {
    int count = *((int*)arg);
    int i;

    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);
    }

    return NULL;
}

void* printABC(void* arg) {
    int count = *((int*)arg);
    int i;

    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);
    }

    return NULL;
}

int main() {
    pthread_t t1, t2, t3;
    int count = 50;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_create(&t1, NULL, printA, &count);
    pthread_create(&t2, NULL, printB, &count);
    pthread_create(&t3, NULL, printC, &count);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}

在这个例子中,我们创建了三个线程,分别负责循环打印字母 A、B、C。使用互斥锁 mutex 和条件变量 cond 来实现线程间的同步。每个线程在打印自己的字母之前,会先检查 i 的值来确定是否轮到自己打印,如果不是则调用 pthread_cond_wait() 进入等待状态。当条件满足时,调用 pthread_cond_signal() 唤醒其他线程,并释放互斥锁 mutex,然后打印自己的字母。最后,主线程调用 pthread_join() 来等待三个线程的结束

代码实现三个线程循环打印 ABC重复 50 次 用c语言

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

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