首页 > 解决方案 > 使用 pthread 从缓冲区写入和读取

问题描述

我正在尝试使用 pthread。在下面的代码中,我定义了两个全局变量(arg1 和 arg2),在主函数中,我开始用 1 填充 arg2 的每个元素。我希望 pthread 在 arg2 的第 101 个元素被填充后立即打印它主要的。但是 pthread 什么也没打印。实际上 arg1 的变化并没有跟随 pthread 并且 pthread 假设 arg1 为 0。如何激活 pthread 以便当我在 main 中写入缓冲区时,pthread 同时开始从缓冲区读取?

提前致谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#include <pthread.h>


struct arg_struct {
    int arg1;
    int arg2[1000];
};

//volatile int arg1;

//int arg2[1000];

void *ProcessThread (void *arguments){
    struct arg_struct *args = arguments;

    if( args -> arg1==100) {
        printf("%d",  args -> arg2[ args -> arg1]);
    }
    pthread_exit(NULL);
    return NULL;
}

void main(){
    struct arg_struct args;

    pthread_t thread1;
    void *thread_status;
    pthread_create(&thread1, NULL, ProcessThread, (void *)&args);

    for ( args.arg1=0; args.arg1<1000; args.arg1++){
        args.arg2[args.arg1] =1;
    }
    pthread_join(thread1,&thread_status);
}

标签: clinuxpthreadspthread-joinpthread-barriers

解决方案


当您进入 for 循环时,线程将终止。arg1中仍未初始化ProcessThread。您可以使用带有 sleep 功能的 while 循环来定期测试条件。


推荐阅读