两线程读写数组

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

#define ARRAY_SIZE 10

int shared_array[ARRAY_SIZE]; 
pthread_mutex_t mutex;        
void *write_data(void *arg)
{
    int thread_id = *(int *)arg;
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        pthread_mutex_lock(&mutex);           
        shared_array[i] = thread_id * 10 + i; 
        printf("线程 %d 写入数据: %d\n", thread_id, shared_array[i]);
        pthread_mutex_unlock(&mutex); 
        sleep(1);                    
    }
    return NULL;
}

int main()
{
    pthread_t thread1, thread2;
    int thread_id1 = 1;
    int thread_id2 = 2;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&thread1, NULL, write_data, (void *)&thread_id1);
    pthread_create(&thread2, NULL, write_data, (void *)&thread_id2);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    printf("最终数组内容:\n");
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        printf("%d ", shared_array[i]);
    }
    printf("\n");
    pthread_mutex_destroy(&mutex);
    return 0;
}

posted on 2024-08-19 23:29  wessf  阅读(5)  评论(0编辑  收藏  举报