两线程读写数组

#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   wessf  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示