Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

In số theo thứ tự dùng đồng bộ thread

Tạo n thread, in 1..n theo thứ tự lặp lại. Dùng mutex + condition variable đồng bộ.

Code ví dụ

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t* cond = NULL;
int threads;
volatile int count = 0;

void* sync_thread(void* num) {
    int id = *(int*)num;
    while(1) {
        pthread_mutex_lock(&mutex);
        if (id != count)
            pthread_cond_wait(&cond[id], &mutex);
        printf("%d ", id+1);
        count = (count+1) % threads;
        pthread_cond_signal(&cond[count]);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    scanf("%d", &threads);
    cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)*threads);
    pthread_t* tid = (pthread_t*)malloc(sizeof(pthread_t)*threads);
    int* arr = (int*)malloc(sizeof(int)*threads);
    for(int i=0;i

Kết quả (5 thread)

1 2 3 4 5 1 2 3 4 5 ...