孤问尘
孤问尘
Published on 2025-01-13 / 0 Visits
0
0

两组任务执行

一共有两组,每组三个任务,分别需要不同的时间完成,要进行任务调度

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int time_slot = 0;

void *task_A(void *arg) {
    int id = *((int*)arg);
    while (1) {
        pthread_mutex_lock(&mutex);
        if (time_slot == 0 || time_slot == 3 || time_slot == 4) {
            printf("A(%d) 在第(%d)时间段工作\n", id, time_slot);
            time_slot++;
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);
        usleep(rand() % 1000000);
    }
    return NULL;
}

void *task_B(void *arg) {
    int id = *((int*)arg);
    while (1) {
        pthread_mutex_lock(&mutex);
        if (time_slot == 1 || time_slot == 2 || time_slot == 5) {
            printf("B(%d) 在第(%d)时间段工作\n", id, time_slot);
            time_slot++;
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
 srand(time(NULL));
    pthread_t threads[6];
    int i;
    int id_A[3] = {0, 1, 2};
    int id_B[3] = {0, 1, 2};

    for (i = 0; i < 3; i++) {
        pthread_create(&threads[i], NULL, task_A, &id_A[i]);
    }
    for (i = 0; i < 3; i++) {
        pthread_create(&threads[i+3], NULL, task_B, &id_B[i]);
    }

    for (i = 0; i < 6; i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}


Comment